2011/05/29

NSURLConnectionで自己認証証明書回避について

アプリとサーバを組み合わせたシステムを開発するとき、
まだSSLの証明書が正式なものではないことがよくある。
この場合は自己認証証明書を使用するのだが、普通にNSURLConnectionとかでアクセスするとエラーで取得できない。
↓こんなエラー
Error Domain=NSURLErrorDomain Code=-1202

そのための回避方法は以下の通り
- (void) httpRequest:(NSURL*)url
{
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self]; 
}

#pragma mark - NSURLConnectionDelegate
// 以下 SSL回避 ...
- (BOOL) connection:(NSURLConnection *)connection 
canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection 
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] 
             forAuthenticationChallenge:challenge];
    }
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

あと、よく見かける方法はNSURLRequestをオーバーライドする方法。
@implementation NSURLRequest(SSL)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host {
    // do some filter based off of "host" here
    return YES;
}
@end
/*NSURLRequestをオーバーライドする方法は正直よく分からない。。
何故かうまくいかないんだよね(´・ω・`)*/

ちなみに、アプリ申請時にはこのあたりはコメントアウトするなりして無効にすること。

2 件のコメント:

  1. のんだくれ2012年7月12日 19:19

    kumityonさん
    ありがとう!
    助かりました!

    返信削除
    返信
    1. コメント有り難うございます!
      お役に立てたようでなによりです(´∀`)

      削除