当前位置:  开发笔记 > 后端 > 正文

如何在swift中向服务器发出HTTPS请求?

如何解决《如何在swift中向服务器发出HTTPS请求?》经验,为你挑选了1个好方法。

我有服务器证书和客户端证书需要包含在请求中以验证服务器是否有任何教程或参考在swift中发出此类请求

我能够在java中做,但我是swift的新手我希望swift中的资源能够进行身份验证并向服务器发出请求

我的java代码来进行ssl配置:

SslConfigurator  sslConfig = SslConfigurator.newInstance().securityProtocol("protocol")
                .keyStoreFile("/path").keyStorePassword("password").keyStoreType("JKS")
                .trustStoreFile("path");

Karlos.. 8

我正在使用iOS本机库.您可以使用以下功能进行连接以及服务器证书和客户端证书身份验证:

     func ConnectionRequest(jsonString:NSDictionary, callback: (NSDictionary, String!) -> Void) {
    let request = NSMutableURLRequest(URL: NSURL(string: "https://example.com:9222")!)

    var result = NSDictionary()

    do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonString, options: [])
    } catch{
        request.HTTPBody = nil
    }
    request.timeoutInterval = 20.0 //(number as! NSTimeInterval)
    request.HTTPMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("gzip", forHTTPHeaderField: "Accept-encoding")

    let configuration =
    NSURLSessionConfiguration.defaultSessionConfiguration()

    let session = NSURLSession(configuration: configuration,
        delegate: self,
        delegateQueue:NSOperationQueue.mainQueue())
    print("--------------------------------NSURLSession Request-------------------------------------------------->:\n \(jsonString)")
    print(NSDate())


    let task = session.dataTaskWithRequest(request){
        (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

        if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode != 200 {
                print("response was not 200: \(response)")
                return
            }
            else
            {
                print("response was 200: \(response)")

                print("Data for 200: \(data)")

                // In the callback you can return the data/response 
                callback(data, nil)
                return
            }
        }
        if (error != nil) {
            print("error request:\n \(error)")
            //Here you can return the error and handle it accordingly
            return
        }

    }
    task.resume()

}

以下代码更改适用于自签名SSL证书

  func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {

    if challenge.protectionSpace.authenticationMethod == (NSURLAuthenticationMethodServerTrust) {


    let serverTrust:SecTrustRef = challenge.protectionSpace.serverTrust!
    let certificate: SecCertificateRef = SecTrustGetCertificateAtIndex(serverTrust, 0)!
    let remoteCertificateData = CFBridgingRetain(SecCertificateCopyData(certificate))!
    let cerPath: String = NSBundle.mainBundle().pathForResource("example.com", ofType: "cer")!
    let localCertificateData = NSData(contentsOfFile:cerPath)!


        if (remoteCertificateData.isEqualToData(localCertificateData) == true) {
            let credential:NSURLCredential = NSURLCredential(forTrust: serverTrust)

            challenge.sender?.useCredential(credential, forAuthenticationChallenge: challenge)


            completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!))

        } else {

            completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
        }
    }
    else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate
    {

        let path: String = NSBundle.mainBundle().pathForResource("client", ofType: "p12")!
        let PKCS12Data = NSData(contentsOfFile:path)!


        let identityAndTrust:IdentityAndTrust = self.extractIdentity(PKCS12Data);



            let urlCredential:NSURLCredential = NSURLCredential(
                identity: identityAndTrust.identityRef,
                certificates: identityAndTrust.certArray as? [AnyObject],
                persistence: NSURLCredentialPersistence.ForSession);

            completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, urlCredential);




    }
    else
    {
        completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil);
    }
}

 struct IdentityAndTrust {

    var identityRef:SecIdentityRef
    var trust:SecTrustRef
    var certArray:AnyObject
}

func extractIdentity(certData:NSData) -> IdentityAndTrust {
    var identityAndTrust:IdentityAndTrust!
    var securityError:OSStatus = errSecSuccess

    let path: String = NSBundle.mainBundle().pathForResource("client", ofType: "p12")!
    let PKCS12Data = NSData(contentsOfFile:path)!
    let key : NSString = kSecImportExportPassphrase as NSString
    let options : NSDictionary = [key : "xyz"]
    //create variable for holding security information
    //var privateKeyRef: SecKeyRef? = nil

    var items : CFArray?

     securityError = SecPKCS12Import(PKCS12Data, options, &items)

    if securityError == errSecSuccess {
        let certItems:CFArray = items as CFArray!;
        let certItemsArray:Array = certItems as Array
        let dict:AnyObject? = certItemsArray.first;
        if let certEntry:Dictionary = dict as? Dictionary {

            // grab the identity
            let identityPointer:AnyObject? = certEntry["identity"];
            let secIdentityRef:SecIdentityRef = identityPointer as! SecIdentityRef!;
            print("\(identityPointer)  :::: \(secIdentityRef)")
            // grab the trust
            let trustPointer:AnyObject? = certEntry["trust"];
            let trustRef:SecTrustRef = trustPointer as! SecTrustRef;
            print("\(trustPointer)  :::: \(trustRef)")
            // grab the cert
            let chainPointer:AnyObject? = certEntry["chain"];
            identityAndTrust = IdentityAndTrust(identityRef: secIdentityRef, trust: trustRef, certArray:  chainPointer!);
        }
    }
    return identityAndTrust;
}

在info.plist文件中完成的更改

     



    NSExceptionDomains
    
        amazonaws.com.cn
        
            NSIncludesSubdomains
            
            NSThirdPartyExceptionRequiresForwardSecrecy
            
            NSThirdPartyExceptionMinimumTLSVersion
            TLSv1.0
        
        amazonaws.com
        
            NSIncludesSubdomains
            
            NSThirdPartyExceptionRequiresForwardSecrecy
            
            NSThirdPartyExceptionMinimumTLSVersion
            TLSv1.0
        
        xyz.com
        
            NSExceptionAllowsInsecureHTTPLoads
            
            NSTemporaryExceptionMinimumTLSVersion
            TLSv1.2
            NSRequiresCertificateTransparency
            
            NSIncludesSubdomains
            
        
    
    NSAllowsArbitraryLoads
    


希望这会有所帮助.



1> Karlos..:

我正在使用iOS本机库.您可以使用以下功能进行连接以及服务器证书和客户端证书身份验证:

     func ConnectionRequest(jsonString:NSDictionary, callback: (NSDictionary, String!) -> Void) {
    let request = NSMutableURLRequest(URL: NSURL(string: "https://example.com:9222")!)

    var result = NSDictionary()

    do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonString, options: [])
    } catch{
        request.HTTPBody = nil
    }
    request.timeoutInterval = 20.0 //(number as! NSTimeInterval)
    request.HTTPMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("gzip", forHTTPHeaderField: "Accept-encoding")

    let configuration =
    NSURLSessionConfiguration.defaultSessionConfiguration()

    let session = NSURLSession(configuration: configuration,
        delegate: self,
        delegateQueue:NSOperationQueue.mainQueue())
    print("--------------------------------NSURLSession Request-------------------------------------------------->:\n \(jsonString)")
    print(NSDate())


    let task = session.dataTaskWithRequest(request){
        (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

        if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode != 200 {
                print("response was not 200: \(response)")
                return
            }
            else
            {
                print("response was 200: \(response)")

                print("Data for 200: \(data)")

                // In the callback you can return the data/response 
                callback(data, nil)
                return
            }
        }
        if (error != nil) {
            print("error request:\n \(error)")
            //Here you can return the error and handle it accordingly
            return
        }

    }
    task.resume()

}

以下代码更改适用于自签名SSL证书

  func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {

    if challenge.protectionSpace.authenticationMethod == (NSURLAuthenticationMethodServerTrust) {


    let serverTrust:SecTrustRef = challenge.protectionSpace.serverTrust!
    let certificate: SecCertificateRef = SecTrustGetCertificateAtIndex(serverTrust, 0)!
    let remoteCertificateData = CFBridgingRetain(SecCertificateCopyData(certificate))!
    let cerPath: String = NSBundle.mainBundle().pathForResource("example.com", ofType: "cer")!
    let localCertificateData = NSData(contentsOfFile:cerPath)!


        if (remoteCertificateData.isEqualToData(localCertificateData) == true) {
            let credential:NSURLCredential = NSURLCredential(forTrust: serverTrust)

            challenge.sender?.useCredential(credential, forAuthenticationChallenge: challenge)


            completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!))

        } else {

            completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
        }
    }
    else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate
    {

        let path: String = NSBundle.mainBundle().pathForResource("client", ofType: "p12")!
        let PKCS12Data = NSData(contentsOfFile:path)!


        let identityAndTrust:IdentityAndTrust = self.extractIdentity(PKCS12Data);



            let urlCredential:NSURLCredential = NSURLCredential(
                identity: identityAndTrust.identityRef,
                certificates: identityAndTrust.certArray as? [AnyObject],
                persistence: NSURLCredentialPersistence.ForSession);

            completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, urlCredential);




    }
    else
    {
        completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil);
    }
}

 struct IdentityAndTrust {

    var identityRef:SecIdentityRef
    var trust:SecTrustRef
    var certArray:AnyObject
}

func extractIdentity(certData:NSData) -> IdentityAndTrust {
    var identityAndTrust:IdentityAndTrust!
    var securityError:OSStatus = errSecSuccess

    let path: String = NSBundle.mainBundle().pathForResource("client", ofType: "p12")!
    let PKCS12Data = NSData(contentsOfFile:path)!
    let key : NSString = kSecImportExportPassphrase as NSString
    let options : NSDictionary = [key : "xyz"]
    //create variable for holding security information
    //var privateKeyRef: SecKeyRef? = nil

    var items : CFArray?

     securityError = SecPKCS12Import(PKCS12Data, options, &items)

    if securityError == errSecSuccess {
        let certItems:CFArray = items as CFArray!;
        let certItemsArray:Array = certItems as Array
        let dict:AnyObject? = certItemsArray.first;
        if let certEntry:Dictionary = dict as? Dictionary {

            // grab the identity
            let identityPointer:AnyObject? = certEntry["identity"];
            let secIdentityRef:SecIdentityRef = identityPointer as! SecIdentityRef!;
            print("\(identityPointer)  :::: \(secIdentityRef)")
            // grab the trust
            let trustPointer:AnyObject? = certEntry["trust"];
            let trustRef:SecTrustRef = trustPointer as! SecTrustRef;
            print("\(trustPointer)  :::: \(trustRef)")
            // grab the cert
            let chainPointer:AnyObject? = certEntry["chain"];
            identityAndTrust = IdentityAndTrust(identityRef: secIdentityRef, trust: trustRef, certArray:  chainPointer!);
        }
    }
    return identityAndTrust;
}

在info.plist文件中完成的更改

     



    NSExceptionDomains
    
        amazonaws.com.cn
        
            NSIncludesSubdomains
            
            NSThirdPartyExceptionRequiresForwardSecrecy
            
            NSThirdPartyExceptionMinimumTLSVersion
            TLSv1.0
        
        amazonaws.com
        
            NSIncludesSubdomains
            
            NSThirdPartyExceptionRequiresForwardSecrecy
            
            NSThirdPartyExceptionMinimumTLSVersion
            TLSv1.0
        
        xyz.com
        
            NSExceptionAllowsInsecureHTTPLoads
            
            NSTemporaryExceptionMinimumTLSVersion
            TLSv1.2
            NSRequiresCertificateTransparency
            
            NSIncludesSubdomains
            
        
    
    NSAllowsArbitraryLoads
    


希望这会有所帮助.

推荐阅读
云聪京初瑞子_617
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有