UE5でOAuth 2.0 PKCEを実装する@windows
PKCE
RFC 7636を参照してください。
認証フロ-
簡単に説明すると、UE内でローカルサーバーを立てておき、webブラウザからデータを受け取ります。
問題点
UEのデフォのランダム生成関数だと色々問題がある。
RFC 7636の Code Verifierの生成にはこうある。
4.1. Client Creates a Code Verifier
The client first creates a code verifier, "code_verifier", for each
OAuth 2.0 [RFC6749] Authorization Request, in the following manner:
code_verifier = high-entropy cryptographic random STRING using the
unreserved characters [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~"
from Section 2.3 of [RFC3986], with a minimum length of 43 characters
and a maximum length of 128 characters.
ABNF for "code_verifier" is as follows.
code-verifier = 43*128unreserved
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
ALPHA = %x41-5A / %x61-7A
DIGIT = %x30-39
NOTE: The code verifier SHOULD have enough entropy to make it
impractical to guess the value. It is RECOMMENDED that the output of
a suitable random number generator be used to create a 32-octet
sequence. The octet sequence is then base64url-encoded to produce a
43-octet URL safe string to use as the code verifier.
code_verifier =予約されていない文字を使用した高エントロピー暗号ランダム文字列[A-Z] / [a-z] / [0-9] / ”-” / ”。” [RFC3986]のセクション2.3の/ ”_” / ”〜“。最小長は43文字、最大長は128文字です。
コードベリファイアには、値を推測するのを非実用的にするのに十分なエントロピーが必要です(SHOULD)
UEの乱数生成アルゴリズムはalweiさんとDM(本物)さんのツイートが参考になる。 https://x.com/aizen76/status/1193935976948621314
windowsだったらBCryptGenRandomとかが使えるらしいが、os依存になってしまうので避けたい。
解決策
乱数及びハッシュ関数を計算するクラウドAPIを生やした。 httpsで通信する。cloudflare workersで実装
プラグイン
ローカルhttpサーバーを建てる用 https://www.fab.com/ja/listings/d95fcaab-6699-449a-a742-05564bc9959c
HttpBlueprint,Json Blueprint Utilitiesを有効化(エンジンプラグイン)
ログイン処理
auth codeの取得
たいして難しい処理はしません。 まずどうにかして上記の条件を満たすcode_verifierとcode_challengeを取得します。
その後Launch URlするだけです。
https://{cognito_domain}/oauth2/authorize?client_id={cognito_client_id}&response_type=code&scope=openid+email&redirect_uri=http://localhost:{server_port}/callback&code_challenge={code_challenge}&code_challenge_method=S256
redirect_uri=http://localhost:{server_port}/callback
UE側でリダイレクトを受け取る
ここで指定したURLにGETリクエストが来るので、これをUE側で待ち受けます。
Query Paramsにcodeで検索をかけます
exchange code
もらったauth codeを元にcode_verifierをPOSTリクエストで投げます。
https://{cognito_domain}/oauth2/token
grant_type=authorization_code&client_id={cognito_client_id}&code={returned_code}&redirect_uri=http://localhost:{server_port}/Fcallback&code_verifier={code_verifier}
展望
モバイルで実装するにはUniversal Links/App Linksで同様に実装すると良さそう。プラグインがこれもあるのだが、1万弱して高いので次の給料日まで待つことにする。