如何快速向服务器发出HTTPS请求? [英] How to make a HTTPS request to a server in swift?

查看:96
本文介绍了如何快速向服务器发出HTTPS请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有服务器证书和客户端证书,需要在请求中包括以对服务器进行身份验证,是否有任何教程或参考资料可以迅速进行此类请求

I am having server certificate and client certificate that needs to be included in the request to authenticate the server is there any tutorial or reference to make such requests in swift

我能够使用Java进行操作,但是我是Swift的新手,我希望Swift中的资源能够进行身份验证并向服务器发出请求

i am able to do in java but i am new to swift i want a resource in swift to authenticate and make requests to server

我的Java代码进行ssl配置:

my java code to make ssl configuration:

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

推荐答案

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

I am using the iOS native library. You can use the following function for connection and server certificate and client certificate authentication:

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证书配合使用的代码更改

Following are the code changes which work fine with Self Signed SSL certificate

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<String, AnyObject> {

            // 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文件中完成的更改

Changes done in the info.plist file

<?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>amazonaws.com.cn</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSThirdPartyExceptionMinimumTLSVersion</key>
            <string>TLSv1.0</string>
        </dict>
        <key>amazonaws.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSThirdPartyExceptionMinimumTLSVersion</key>
            <string>TLSv1.0</string>
        </dict>
        <key>xyz.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSRequiresCertificateTransparency</key>
            <false/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
    <key>NSAllowsArbitraryLoads</key>
    <false/>
</dict>
</plist>

希望这会有所帮助.

这篇关于如何快速向服务器发出HTTPS请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆