ios HTTPS 설정 (단방향 검증, 프로젝트 인증서 필요 없음)

2878 단어

이 문제는 나를 이틀 동안 함정에 빠뜨렸어!인터넷에서 각종 검색을 해도 해결되지 않았다.


백엔드 단방향 검증, 자체 서명 인증서!

업데이트됨: oc AFNetworking HTTPS


클라이언트가 수행해야 할 작업:


1. 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
        }()

2. UIWebView 설정https(내 프로젝트는 모두 swift에서 썼기 때문에 swift 코드를 붙이고oc가 직접 돌려라!)


NSURLconnection Delegate 는
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는 더 찾기 힘들어!

3. OC AFNetworking HTTPS 프로젝트에 인증서를 추가할 필요가 없고 단방향 검증 요청에 코드를 추가하면 OK

//  HTTPS
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    [securityPolicy setValidatesDomainName:NO];
    securityPolicy.allowInvalidCertificates = YES; //      YES
    manager.securityPolicy = securityPolicy;



나 는 풋내기 인데, 어디 서 환영하지 않겠는가

좋은 웹페이지 즐겨찾기