iOS进行Basic认证与NTLM认证

时间:2021-07-20 18:12:42

一、iOS进行Basic认证

只需要在NSMutableURLRequest的Header中添加认证所需的Username和password.

NSMutableURLRequest *webReq = [NSMutableURLRequest requestWithURL:self.url];
//添加认证信息
NSString *authString = [[[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
authString = [NSString stringWithFormat: @"Basic %@", authString];
[webReq setValue:authString forHTTPHeaderField:@"Authorization"];
[self.webView loadRequest:webReq];

二、iOS进行NTLM认证

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{

    NSLog(@"开始认证...");

    NSString *authMethod = [[challenge protectionSpace] authenticationMethod];
NSLog(@"%@认证...",authMethod);   if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if ([challenge previousFailureCount] == ) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}else{
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge,nil);
}
} if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodNTLM]) {
if ([challenge previousFailureCount] == ) {
NSURLCredential *credential = [NSURLCredential credentialWithUser:kGlobal.userInfo.sAccount password:kGlobal.userInfo.sPassword persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}else{
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge,nil);
}
} NSLog(@"认证结束...");
}

Update on  2017-01-13

NTLM认证的整个过程需要3次HTTP请求,使用Charles抓包发现正常的NTLM认证过程需要三次HTTP请求,前两次请求都会显示不成功,第三次会返回正确的数据。前两次请求实际上是客户端和服务器正在建立信任的一个过程。具体的NTLM的认证过程可以参考链接:https://blogs.msdn.microsoft.com/chiranth/2013/09/20/ntlm-want-to-know-how-it-works/

使用Charles抓包验证NTLM认证截图:

iOS进行Basic认证与NTLM认证