zoukankan      html  css  js  c++  java
  • iOS进行Basic认证与NTLM认证

    一、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] == 0) {
                NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
                completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
            }else{
                completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge,nil);
            }
        }
        
        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodNTLM]) {
            if ([challenge previousFailureCount] == 0) {
                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认证截图:

  • 相关阅读:
    angularJs实现级联操作
    FastDFS简单入门小demo
    FastDFS初步认识--上传下载流程介绍
    什么是spu和sku
    centOS7 flask项目布署
    Error: Another program is already listening on a port that one of our HTTP servers is configured to use. Shut this program down first before starting supervisord.
    gunicorn+nginx配置方法
    supervisor的使用
    【linux】杀掉进程命令
    CentOS7 nginx安装与卸载
  • 原文地址:https://www.cnblogs.com/wobuyayi/p/6178361.html
Copyright © 2011-2022 走看看