Certificate Invalid Issue with Alamofire 4.0

后端 未结 2 940
说谎
说谎 2021-01-12 14:24

I am trying to consume web services for my iOS app over https. The web server uses a self signed certificate.

When consuming the web service, I get the error “certif

2条回答
  •  长发绾君心
    2021-01-12 14:49

    I modified my code like below and it worked. I referred Swift: How to Make Https Request Using Server SSL Certificate for fixing this issue.

           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)")
                           }
                      }
            
            
            
                 }
            }
    

    You should also configure your plist as below

     
    
    
    
        NSExceptionDomains
        
            devportal
            
                NSTemporaryExceptionMinimumTLSVersion
                TLSv1.2
                NSIncludesSubdomains
                
                NSExceptionRequiresForwardSecrecy
                
                NSExceptionAllowsInsecureHTTPLoads
                
            
        
        NSAllowsArbitraryLoads
        
    
    
    

    Do not enter IP or port numbers in your NSExceptiondomains. It won't work. If you are trying to connect to a web server with IP address, map the IP address to a domain by adding a host entry in etc/hosts file in your mac and then use the domain name in NSExceptionDomains

    IMPORTANT: Do not use this code in production as this puts your users information at risk, by bypassing auth challenge.

提交回复
热议问题