您的位置:首页 > 理论基础 > 计算机网络

ios 配置HTTPS (单向验证,工程不需要加证书)

2017-02-23 22:02 639 查看

这个问题坑了我两天啊!网上各种搜,也没解决了。

后台单向验证,自签名证书!

已更新 : oc AFNetworking  适配 HTTPS

客户端需要做的事情:

一、swift   Alamofire网络请求

在请求方法前面加上以下代码即可:
let manager: Alamofire.Manager = {
let manager = Alamofire.Manager.sharedInstance
manager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?

if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = NSURLSessionAuthChallengeDisposition.UseCredential
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
credential = manager.session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)

if credential != nil {
disposition = .UseCredential
}
}
}
return (disposition, credential)
}
return manager
}()

二、 UIWebView 配置https(因为我的工程全是swift写的,贴上swift代码,oc自己转吧!)

主要实现NSURLConnectionDelegate两个代理方法:

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool {
return (protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust)
}

func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
challenge.sender!.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!), forAuthenticationChallenge: challenge)
challenge.sender!.continueWithoutCredentialForAuthenticationChallenge(challenge)
}

}
这样就搞定了 ,坑了我两天啊,swift的更是不好找!

三、 OC   AFNetworking 适配HTTPS  工程不需要添加证书  单向验证  请求处加上一下代码 就OK

//适配HTTPS
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
[securityPolicy setValidatesDomainName:NO];
securityPolicy.allowInvalidCertificates = YES; //还是必须设成YES
manager.securityPolicy = securityPolicy;



本人菜鸟,哪不对欢迎提出
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  swift ios HTTPS配置