Trust Invalid Certificate with DisableEvaluation on Alamofire












2















I need to reach an API which has a invalid certificate and a basic Auth. As I searched, I needed to write custom SessionManager and add an value to plist file. After days of search and lots of posts, I can't still reach the API.



struct CustomManagerClass{

static let instance = CustomManagerClass()
var sessionManager : SessionManager = {

let serverTrustPolicies: [String: ServerTrustPolicy] = [
"baseurl.com:8443": .disableEvaluation
]

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

return manager
}()


Plist File:



<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>baseurl.com</key>
<dict>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>


How I call it:



CustomManagerClass.instance.sessionManager.request(route).responseJSON(completionHandler: { (result) in
completion(result)
}) //Route in here is a ServiceConfiguration class which defines http method, parameters and basic auth.


It still returns;




Task <4CE5991B-2650-471C-AB77-69D54B8E36F3>.<1> finished with error - code: -1202
The certificate for this server is invalid. You might be connecting to a server that is pretending to be “baseurl.com” which could put your confidential information at risk.




Posts I got help:
Certificate Invalid Issue with Alamofire 4.0



How to use Alamofires ServerTrustPolicy.disableEvaluation in swift 3



EDIT: I add below code to trust certificate. Now It returns HTTP 500



 CustomManagerClass.instance.sessionManager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?

print("received challenge")

if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
} else {
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = CustomManagerClass.instance.sessionManager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)

if credential != nil {
disposition = .useCredential
}
}
}

return (disposition, credential)
}









share|improve this question





























    2















    I need to reach an API which has a invalid certificate and a basic Auth. As I searched, I needed to write custom SessionManager and add an value to plist file. After days of search and lots of posts, I can't still reach the API.



    struct CustomManagerClass{

    static let instance = CustomManagerClass()
    var sessionManager : SessionManager = {

    let serverTrustPolicies: [String: ServerTrustPolicy] = [
    "baseurl.com:8443": .disableEvaluation
    ]

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

    return manager
    }()


    Plist File:



    <key>NSAppTransportSecurity</key>
    <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>baseurl.com</key>
    <dict>
    <key>NSTemporaryExceptionMinimumTLSVersion</key>
    <string>TLSv1.2</string>
    <key>NSIncludesSubdomains</key>
    <true/>
    <key>NSExceptionRequiresForwardSecrecy</key>
    <false/>
    <key>NSExceptionAllowsInsecureHTTPLoads</key>
    <true/>
    </dict>
    </dict>


    How I call it:



    CustomManagerClass.instance.sessionManager.request(route).responseJSON(completionHandler: { (result) in
    completion(result)
    }) //Route in here is a ServiceConfiguration class which defines http method, parameters and basic auth.


    It still returns;




    Task <4CE5991B-2650-471C-AB77-69D54B8E36F3>.<1> finished with error - code: -1202
    The certificate for this server is invalid. You might be connecting to a server that is pretending to be “baseurl.com” which could put your confidential information at risk.




    Posts I got help:
    Certificate Invalid Issue with Alamofire 4.0



    How to use Alamofires ServerTrustPolicy.disableEvaluation in swift 3



    EDIT: I add below code to trust certificate. Now It returns HTTP 500



     CustomManagerClass.instance.sessionManager.delegate.sessionDidReceiveChallenge = { session, challenge in
    var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
    var credential: URLCredential?

    print("received challenge")

    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
    disposition = URLSession.AuthChallengeDisposition.useCredential
    credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
    } else {
    if challenge.previousFailureCount > 0 {
    disposition = .cancelAuthenticationChallenge
    } else {
    credential = CustomManagerClass.instance.sessionManager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)

    if credential != nil {
    disposition = .useCredential
    }
    }
    }

    return (disposition, credential)
    }









    share|improve this question



























      2












      2








      2








      I need to reach an API which has a invalid certificate and a basic Auth. As I searched, I needed to write custom SessionManager and add an value to plist file. After days of search and lots of posts, I can't still reach the API.



      struct CustomManagerClass{

      static let instance = CustomManagerClass()
      var sessionManager : SessionManager = {

      let serverTrustPolicies: [String: ServerTrustPolicy] = [
      "baseurl.com:8443": .disableEvaluation
      ]

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

      return manager
      }()


      Plist File:



      <key>NSAppTransportSecurity</key>
      <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
      <key>baseurl.com</key>
      <dict>
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.2</string>
      <key>NSIncludesSubdomains</key>
      <true/>
      <key>NSExceptionRequiresForwardSecrecy</key>
      <false/>
      <key>NSExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      </dict>
      </dict>


      How I call it:



      CustomManagerClass.instance.sessionManager.request(route).responseJSON(completionHandler: { (result) in
      completion(result)
      }) //Route in here is a ServiceConfiguration class which defines http method, parameters and basic auth.


      It still returns;




      Task <4CE5991B-2650-471C-AB77-69D54B8E36F3>.<1> finished with error - code: -1202
      The certificate for this server is invalid. You might be connecting to a server that is pretending to be “baseurl.com” which could put your confidential information at risk.




      Posts I got help:
      Certificate Invalid Issue with Alamofire 4.0



      How to use Alamofires ServerTrustPolicy.disableEvaluation in swift 3



      EDIT: I add below code to trust certificate. Now It returns HTTP 500



       CustomManagerClass.instance.sessionManager.delegate.sessionDidReceiveChallenge = { session, challenge in
      var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
      var credential: URLCredential?

      print("received challenge")

      if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
      disposition = URLSession.AuthChallengeDisposition.useCredential
      credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
      } else {
      if challenge.previousFailureCount > 0 {
      disposition = .cancelAuthenticationChallenge
      } else {
      credential = CustomManagerClass.instance.sessionManager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)

      if credential != nil {
      disposition = .useCredential
      }
      }
      }

      return (disposition, credential)
      }









      share|improve this question
















      I need to reach an API which has a invalid certificate and a basic Auth. As I searched, I needed to write custom SessionManager and add an value to plist file. After days of search and lots of posts, I can't still reach the API.



      struct CustomManagerClass{

      static let instance = CustomManagerClass()
      var sessionManager : SessionManager = {

      let serverTrustPolicies: [String: ServerTrustPolicy] = [
      "baseurl.com:8443": .disableEvaluation
      ]

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

      return manager
      }()


      Plist File:



      <key>NSAppTransportSecurity</key>
      <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
      <key>baseurl.com</key>
      <dict>
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.2</string>
      <key>NSIncludesSubdomains</key>
      <true/>
      <key>NSExceptionRequiresForwardSecrecy</key>
      <false/>
      <key>NSExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      </dict>
      </dict>


      How I call it:



      CustomManagerClass.instance.sessionManager.request(route).responseJSON(completionHandler: { (result) in
      completion(result)
      }) //Route in here is a ServiceConfiguration class which defines http method, parameters and basic auth.


      It still returns;




      Task <4CE5991B-2650-471C-AB77-69D54B8E36F3>.<1> finished with error - code: -1202
      The certificate for this server is invalid. You might be connecting to a server that is pretending to be “baseurl.com” which could put your confidential information at risk.




      Posts I got help:
      Certificate Invalid Issue with Alamofire 4.0



      How to use Alamofires ServerTrustPolicy.disableEvaluation in swift 3



      EDIT: I add below code to trust certificate. Now It returns HTTP 500



       CustomManagerClass.instance.sessionManager.delegate.sessionDidReceiveChallenge = { session, challenge in
      var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
      var credential: URLCredential?

      print("received challenge")

      if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
      disposition = URLSession.AuthChallengeDisposition.useCredential
      credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
      } else {
      if challenge.previousFailureCount > 0 {
      disposition = .cancelAuthenticationChallenge
      } else {
      credential = CustomManagerClass.instance.sessionManager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)

      if credential != nil {
      disposition = .useCredential
      }
      }
      }

      return (disposition, credential)
      }






      ios swift alamofire






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 11:50







      Emre Önder

















      asked Nov 16 '18 at 10:22









      Emre ÖnderEmre Önder

      889625




      889625
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I'd suggest to add this handler for the sessionDidReceiveChallenge event on the SessionManager delegate.



          let challengeHandler: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? = { result, challenge in
          return (.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
          }


          And then assign the closure when you're initializing the manager object in this way.



          manager.delegate.sessionDidReceiveChallenge = challengeHandler


          Also, the serverTrustPolicies can be empty since the handler is going to ignore all the trust challenges it will receive.






          share|improve this answer


























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53335849%2ftrust-invalid-certificate-with-disableevaluation-on-alamofire%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I'd suggest to add this handler for the sessionDidReceiveChallenge event on the SessionManager delegate.



            let challengeHandler: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? = { result, challenge in
            return (.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
            }


            And then assign the closure when you're initializing the manager object in this way.



            manager.delegate.sessionDidReceiveChallenge = challengeHandler


            Also, the serverTrustPolicies can be empty since the handler is going to ignore all the trust challenges it will receive.






            share|improve this answer






























              0














              I'd suggest to add this handler for the sessionDidReceiveChallenge event on the SessionManager delegate.



              let challengeHandler: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? = { result, challenge in
              return (.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
              }


              And then assign the closure when you're initializing the manager object in this way.



              manager.delegate.sessionDidReceiveChallenge = challengeHandler


              Also, the serverTrustPolicies can be empty since the handler is going to ignore all the trust challenges it will receive.






              share|improve this answer




























                0












                0








                0







                I'd suggest to add this handler for the sessionDidReceiveChallenge event on the SessionManager delegate.



                let challengeHandler: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? = { result, challenge in
                return (.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
                }


                And then assign the closure when you're initializing the manager object in this way.



                manager.delegate.sessionDidReceiveChallenge = challengeHandler


                Also, the serverTrustPolicies can be empty since the handler is going to ignore all the trust challenges it will receive.






                share|improve this answer















                I'd suggest to add this handler for the sessionDidReceiveChallenge event on the SessionManager delegate.



                let challengeHandler: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? = { result, challenge in
                return (.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
                }


                And then assign the closure when you're initializing the manager object in this way.



                manager.delegate.sessionDidReceiveChallenge = challengeHandler


                Also, the serverTrustPolicies can be empty since the handler is going to ignore all the trust challenges it will receive.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 22 '18 at 9:22

























                answered Nov 22 '18 at 9:16









                Lorenzo ZanottoLorenzo Zanotto

                1365




                1365
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53335849%2ftrust-invalid-certificate-with-disableevaluation-on-alamofire%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Bressuire

                    Vorschmack

                    Quarantine