Certificate Invalid Issue with Alamofire 4.0

强颜欢笑 提交于 2019-12-01 05:35:18
CrazyDeveloper

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

 <?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>

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!