hachinoBlog

hachinobuのエンジニアライフ

NSURLConnectionでオレオレ証明書(自己署名証明書)を許可する方法

背景

オレオレ証明書を使用している開発機にNSURLConnectionでhttps接続しようとしたら下記エラーが出力された。

NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)

解決方法

NSURLConnectionのデリゲートの - (void)connection:(NSURLConnection )connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge )challenge を実装してやる。

#pragma mark - NSURLConnection Delegate
//開発環境のオレオレ証明書(自己署名証明書)を許可するため
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    //SSL認証だった場合の処理(NSURLAuthenticationMethodHTTPBasicやNSURLAuthenticationMethodHTTPDigestもある)
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        // "hachinobu-test.elasticbeanstalk.com"か確認
        if ([challenge.protectionSpace.host isEqualToString:@"hachinobu-test.elasticbeanstalk.com"]) {
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
        }
    }
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

こうすることでオレオレ証明書を使用している開発機にもアクセスできる。