LoginSignup
2
2

More than 3 years have passed since last update.

iPhoneアプリで自己証明書のサーバーにリクエストを送りたい

Last updated at Posted at 2020-02-27

はじめに

開発環境ではlocalhostに対してAPIリクエストを送って情報を得るケースがあります。
しかし、iPhoneのデフォルトではどのサーバーにもhttpsであればきちんとした証明書を求めます。
証明書関連をしっかりするのをチーム全員に求めるのも酷なので(たまにしか触らない人も出てくるし)、アプリ側で吸収する方法を調べました。

環境

iOS 13.3

ライブラリを使う

Alamofireというライブラリを使用するのが一番楽という結論になりました。
Security関連の設定を楽にできる仕組みが入っているためです。

Alamofireインストール

上記記事を参照ください。
少し前の記事ですが、この記事を記載している時点で同じやり方で特に困りませんでした。

Sessionの生成

AlamofireはSessionを元に動きます。
公式ではAF.requestという形でリクエストを作っていますが、AFの正体はSession.defaultです。
一般的なSessionを作り出しているので、ここを自分で作ったSessionに変えればOKです。
Sessionを作るコードは以下です。
ServerTrustManagerが肝で、これにevaluatorを変更したいhostとServerTrustEvalutingを渡せば勝手に判定してやってくれます。
Evaluatorはいくつか種類がありますので、詳しくは公式を参照ください。

今回は証明書判定をスルーして欲しいので、DisabledEvaluatorを使用します。
DisabledEvaluatorは完全無視なので使用の際には要注意なEvaluatorです。

private let session: Session = {
    let manager = ServerTrustManager(evaluators: ["localhost": DisabledEvaluator()])
    return Session(configuration: URLSessionConfiguration.af.default, serverTrustManager: manager)
}()

こちらはStack Overflowにあったコードを使わせてもらいました。特に変える必要はないのでそのまま使ってます。
https://stackoverflow.com/questions/55543462/how-to-use-alamofires-servertrustpolicy-disableevaluation-in-swift-5-alamofire-5

リクエスト部分

リクエスト部分は上で作成したSessionを使ってリクエストすればOKです。

self.session.request("https://localhost/api/v1/login", method: .post).response { response in
    print(response)
}

Evaluatorのhostを変更してリクエストを送ってエラーが出て、localhostの際にはエラー出ずにリクエストが送れていますので、これで大丈夫そうです。
なお、証明書エラーになった際は以下のようなエラーが出ます。

failure(Alamofire.AFError.serverTrustEvaluationFailed(reason: Alamofire.AFError.ServerTrustFailureReason.noRequiredEvaluator(host: "localhost")))
2020-02-27 18:07:19.829669+0900 qasee-ios[92585:4214289] Task <630403A5-077F-481E-AD99-9CB312F60676>.<1> HTTP load failed, 0/0 bytes (error code: -999 [1:89])
2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2