iOSでオレオレ証明書を許可する
WebViewとかで普通に https://www.google.co.jp/にリクエストを投げると問題なくページは表示されるのに、自分とこのサーバにhttpsでアクセスしたとたんに何も表示されず、コンソールログに下記のようなエラーが表示されました。
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813) |
そこで少し調べたところ、どうやらオレオレ証明書を発行しているところにhttpsでアクセスするのがダメだったみたい。。。
確かに自分とこのサーバは開発環境っていうこともあって正規の証明書は発行してなかったので、
これかー、という感じでした。
対応としては、リクエストを送っているところにConnectionのメソッドをオーバーライドする感じで解決。
// URL生成 NSURL *url = [NSURL URLWithString:@"https://www.sample.co.jp"]; // リクエスト生成 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // Connectionをデリゲート [NSURLConnection connectionWithRequest:request delegate:self]; // Connectionのメソッドをオーバーライド - (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]) { // "www.sample.co.jp"か確認 if ([challenge.protectionSpace.host isEqualToString:@"www.sample.co.jp"]) { [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; } } [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; }
参考:
http://programmers-egg.blogspot.jp/2011/05/nsurlconnection.html
http://stackoverflow.com/questions/933331/how-to-use-nsurlconnection-to-connect-with-ssl-for-an-untrusted-cert