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认证截图:

  • 相关阅读:
    视觉三维重建中不同三角网格视角的选择
    最小二乘求解常数k使得kx=y(x,y为列向量)
    STL常用
    2D-2D:对极几何 基础矩阵F 本质矩阵E 单应矩阵H
    Ubuntu常用软件
    ubuntu linux 安装分区
    单向链表
    1.ssm web项目中的遇到的坑--自定义JQuery插件(slide menu)
    模板引擎freemarker的使用(二)
    模板引擎freemarker的使用(一)
  • 原文地址:https://www.cnblogs.com/wobuyayi/p/6178361.html
Copyright © 2011-2022 走看看