How to do authentication in UIWebView properly?

后端 未结 5 1917
离开以前
离开以前 2020-12-02 15:49

I would like to support HTTP Basic Authentication in my UIWebView.

At the moment, I am canceling requests in

webView:shouldStartLoadWithRequest:navig

5条回答
  •  遥遥无期
    2020-12-02 16:48

    I've just implemented this by setting basic auth credentials using an NSMutableURLRequest for the UIWebView. This also avoids the round trip incurred when implementing sharedCredentialStorage (of course there are tradeoffs involved).

    Solution:

        NSString *url = @"http://www.my-url-which-requires-basic-auth.io"
        NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
        NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
        NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]];
        NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
        [mutableRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
        NSURLRequest *request = [mutableRequest copy];
        NSURLRequest *request = [NSURLRequest basicAuthHTTPURLRequestForUrl:url];
        [self.webView loadRequest:request];
    

    You can grab the NSData+Base64 category which implements the base64EncodedString for NSData from Matt Gallagher's page (it was at the bottom of the blog post when I downloaded it)

提交回复
热议问题