iOS Objective-C异步HTTP Basic Auth后UIWebView链接跳转失效修复咨询
修复UIWebView同域认证页面跳转问题(HTTP Basic认证)
方案1:在shouldStartLoadWithRequest中手动附加认证头
UIWebView发起同域子请求时,不会自动携带初始请求的Authorization头,需手动判断并添加:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { // 替换为你的目标服务域名/端口 NSURL *baseDomainURL = [NSURL URLWithString:@"https://your-target-domain.com"]; // 判断是否为同域请求 if ([request.URL.host isEqualToString:baseDomainURL.host] && request.URL.port == baseDomainURL.port) { // 从本地存储(如Keychain)读取预存的用户名密码,不要硬编码 NSString *authString = [NSString stringWithFormat:@"%@:%@", @"your-username", @"your-password"]; NSData *authData = [authString dataUsingEncoding:NSUTF8StringEncoding]; NSString *authHeader = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]]; NSMutableURLRequest *mutableReq = [request mutableCopy]; [mutableReq setValue:authHeader forHTTPHeaderField:@"Authorization"]; [webView loadRequest:mutableReq]; return NO; // 拦截原请求,用带认证头的新请求加载 } return YES; // 外部链接或非认证请求正常放行 }
方案2:通过NSURLCredentialStorage持久化凭证
让系统自动管理认证凭证,同域后续请求会自动携带:
// 在NSURLConnection/NSURLSession的认证回调中执行 - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic]) { NSURLCredential *credential = [NSURLCredential credentialWithUser:@"your-username" password:@"your-password" persistence:NSURLCredentialPersistencePermanent]; [[NSURLCredentialStorage sharedCredentialStorage] setCredential:credential forProtectionSpace:challenge.protectionSpace]; [challenge.sender useCredential:credential forAuthenticationChallenge:challenge]; } else { [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; } }
存入后,UIWebView同域请求会自动从凭证库中获取并附加认证头。
方案3:替换为WKWebView(兼容iOS 8+)
UIWebView已被弃用,WKWebView的会话管理更完善,默认保持同域认证状态:
- 替换UIWebView为WKWebView
- 实现
WKNavigationDelegate的认证回调:
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler { if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic]) { NSURLCredential *credential = [NSURLCredential credentialWithUser:@"your-username" password:@"your-password" persistence:NSURLCredentialPersistencePermanent]; completionHandler(NSURLSessionAuthChallengeUseCredential, credential); } else { completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); } }
排查要点
- 确认
index2.html的URL与初始页面完全同域(主机、端口、协议一致) - 用抓包工具(如Charles)查看跳转请求是否携带Authorization头,无则说明凭证未被正确附加
- 若用NSURLSession,确保会话配置使用默认的凭证存储共享策略
内容的提问来源于stack exchange,提问作者doctor
相关产品推荐
相关产品推荐

