2016-11-23 24 views
3

我试图通过https为我的iOS应用程序使用Web服务。 Web服务器使用自签名证书。Alamofire 4.0证书无效问题

使用Web服务时,出现错误“证书无效”。

失败:“它可以把您的机密信息处于危险之中‘错误域= NSURLErrorDomain代码= -1202’此服务器的证书无效,您可能正在连接到一个伪装成是服务器”门户网站

我知道最好的做法是在服务器端修复这个问题,以启用受信任的根CA.但是,由于这是一个临时开发环境,我们正在使用自签名证书。 由于这是ATS问题,我已经在我的info.plist中编辑了ATS,如下所示。

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 
<dict> 
    <key>NSExceptionDomains</key> 
    <dict> 
     <key>devportal</key> 
     <dict> 
      <key>NSTemporaryExceptionMinimumTLSVersion</key> 
      <string>TLSv1.2</string> 
      <key>NSIncludesSubdomains</key> 
      <true/> 
      <key>NSExceptionRequiresForwardSecrecy</key> 
      <false/> 
      <key>NSExceptionAllowsInsecureHTTPLoads</key> 
      <true/> 
     </dict> 
    </dict> 
    <key>NSAllowsArbitraryLoads</key> 
    <false/> 
</dict> 
</plist> 

由于NSException域不会与IP和端口号的工作,我已经创造了我等主机条目/ hosts文件的Web服务器IP和https://192.22.xx.xxx:8443/rest/login

消耗它像 https://devportal:8443/rest/login不是消耗它的

我遵循关于服务器信任策略的alamofire文档,编辑了ATS以允许异常域,但没有为我解决。我已经在这个问题上花了3天时间。我错过了什么吗?有人遇到过类似的问题吗?有没有解决方案?在此先感谢

我使用almofire 4.0,Xcode 8.0。以下是我的代码。

class LoginService{ 
    private static var Manager: Alamofire.SessionManager = { 

      let pathToCert = Bundle.main.path(forResource: "192.22.xx.xxx", ofType: "crt") // Downloaded this certificate and have added to my bundle 
      let localCertificate:NSData = NSData(contentsOfFile: pathToCert!)! 

      // Create the server trust policies 
      let serverTrustPolicies: [String: ServerTrustPolicy] = [ 
       "192.22.xx.xxx": .pinCertificates(
        certificates: [SecCertificateCreateWithData(nil, localCertificate)!], 
        validateCertificateChain: true, 
        validateHost: true 
       ), 

       "devportal:8443": .disableEvaluation 
      ] 

      // Create custom manager 
      let configuration = URLSessionConfiguration.default 
      configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders 
      let manager = Alamofire.SessionManager(
       configuration: URLSessionConfiguration.default, 
       serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) 
     ) 

      return manager 
    }() 



    /** 
     Calls the Login Web Service to authenticate the user 
     */ 
    public func login(username:String, password: String){ 

      let parameters = [ 
       "username": "TEST", 
       "password": "PASSWORD", 
        ] 
      let header: HTTPHeaders = ["Accept": "application/json"] 
      LoginService.Manager.request("https://devportal:8443/rest/login", method: .post, parameters: parameters, encoding: JSONEncoding(options: []),headers :header).responseJSON { response in 
       debugPrint(response) 

       if let json = response.result.value { 
        print("JSON: \(json)") 
       } 
      } 



    } 
} 
+0

您的测试设备是否配置为信任自签名证书?这可以在iOS设置 - >常规 - >配置文件中验证。 –

+0

@Rein我没有在设备上测试它,因为它没有测试准备好。我刚开始开发并在模拟器上运行它。 – CrazyDeveloper

回答

3

我修改了我的代码,如下所示,它工作。我提到了Swift: How to Make Https Request Using Server SSL Certificate来解决这个问题。

 class LoginService{ 
      private static var Manager: Alamofire.SessionManager = { 

        // Create the server trust policies 
        let serverTrustPolicies: [String: ServerTrustPolicy] = [ 

         "devportal:8443": .disableEvaluation 
        ] 

        // Create custom manager 
        let configuration = URLSessionConfiguration.default 
        configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders 
        let manager = Alamofire.SessionManager(
         configuration: URLSessionConfiguration.default, 
         serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) 
       ) 

        return manager 
      }() 



      /** 
       Calls the Login Web Service to authenticate the user 
       */ 
      public func login(username:String, password: String){ 

    // Handle Authentication challenge 

      let delegate: Alamofire.SessionDelegate = LoginService.Manager.delegate 
     delegate.sessionDidReceiveChallenge = { session, challenge in 
       var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling 
       var credential: URLCredential? 
       if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { 
        disposition = URLSession.AuthChallengeDisposition.useCredential 
        credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) 
       } else { 
        if challenge.previousFailureCount > 0 { 
         disposition = .cancelAuthenticationChallenge 
        } else { 
         credential = LoginService.Manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) 
         if credential != nil { 
          disposition = .useCredential 
         } 
        } 
       } 
       return (disposition, credential) 
     } 

//Web service Request  
        let parameters = [ 
         "username": "TEST", 
         "password": "PASSWORD", 
          ] 
        let header: HTTPHeaders = ["Accept": "application/json"] 
        LoginService.Manager.request("https://devportal:8443/rest/login", method: .post, parameters: parameters, encoding: JSONEncoding(options: []),headers :header).responseJSON { response in 
         debugPrint(response) 

         if let json = response.result.value { 
          print("JSON: \(json)") 
         } 
        } 



      } 
     } 

你也应该配置的plist如下

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 
<dict> 
    <key>NSExceptionDomains</key> 
    <dict> 
     <key>devportal</key> 
     <dict> 
      <key>NSTemporaryExceptionMinimumTLSVersion</key> 
      <string>TLSv1.2</string> 
      <key>NSIncludesSubdomains</key> 
      <true/> 
      <key>NSExceptionRequiresForwardSecrecy</key> 
      <false/> 
      <key>NSExceptionAllowsInsecureHTTPLoads</key> 
      <true/> 
     </dict> 
    </dict> 
    <key>NSAllowsArbitraryLoads</key> 
    <false/> 
</dict> 
</plist> 

在NSExceptiondomains不要输入IP或端口号。它不会 工作。如果你试图连接到IP地址为Web服务器, 在你的Mac将在等一个主机条目/主机 文件映射IP地址到域,然后在NSExceptionDomains

重要使用的域名:不要在生产中使用此代码,因为这会让您的用户绕过认证挑战而面临风险。

+0

非常感谢我的工作:-) –