Web UIでサインインを有効にする
前提条件
完全な例については、プロジェクトセットアップのウォークスルーに従ってください。
Auth カテゴリを設定
以下のように auth/resource.ts ファイルを更新して、web UIでのサインインとサインアウト機能を有効にします。
export const auth = defineAuth({ loginWith: { email: true, externalProviders: { callbackUrls: ["myapp://callback/"], logoutUrls: ["myapp://signout/"], }, },});Info.plistを更新
Web UIでのサインインには、Amplifyプラグインが、サインイン UIをwebview内に表示する必要があります。サインインプロセスが完了すると、サインイン UIはアプリにリダイレクトされます。
アプリの Info.plist でこれを有効にする必要があります。Info.plistを右クリックして、Open As > Source Codeを選択します。URL スキームに以下のエントリを追加します:
<plist version="1.0">
<dict> <!-- YOUR OTHER PLIST ENTRIES HERE -->
<!-- ADD AN ENTRY TO CFBundleURLTypes for Cognito Auth --> <!-- IF YOU DO NOT HAVE CFBundleURLTypes, YOU CAN COPY THE WHOLE BLOCK BELOW --> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>myapp</string> </array> </dict> </array>
<!-- ... --> </dict>Xcode 13を使用して新しいSwiftUIアプリを作成する場合、Info.plistなどの設定ファイルは不要です。このファイルが見当たらない場合は、プロジェクトターゲットをクリックし、Info、Url Types の下で、「+」をクリックして新しいURL Typeを追加します。URL Schemsに myapp を追加します。CFBundleURLSchemesのエントリを含むInfo.plistファイルが表示されます。
Web UI サインインを起動
Web UIでサインインを起動する準備ができました。signInWithWebUI APIはpresentationAnchorを必要とし、iOSアプリの場合、アプリのメインUIWindowになります。以下のコード例は、UIViewControllerにいて、self.view.window でUIWindowインスタンスを取得できることを前提としています。
func signInWithWebUI() async { do { let signInResult = try await Amplify.Auth.signInWithWebUI(presentationAnchor: self.view.window!) if signInResult.isSignedIn { print("Sign in succeeded") } } catch let error as AuthError { print("Sign in failed \(error)") } catch { print("Unexpected error: \(error)") }}func signInWithWebUI() -> AnyCancellable { Amplify.Publisher.create { try await Amplify.Auth.signInWithWebUI(presentationAnchor: self.view.window!) }.sink { if case let .failure(authError) = $0 { print("Sign in failed \(authError)") } } receiveValue: { signInResult in if signInResult.isSignedIn { print("Sign in succeeded") } }}サインイン中にプライベートセッションを優先
Amplify 1.6.0以降、Amplify.Auth.signInWithWebUI はiOS 13.0以上では内部で ASWebAuthenticationSession を自動的に使用します。古いiOSバージョンの場合は、SFAuthenticationSession にフォールバックします。
このリリースでは、サインインフロー中に AWSAuthWebUISignInOptions に新しい preferPrivateSession フラグも導入されています。サインイン中に preferPrivateSession が true に設定されている場合、ユーザーはサインアウト時にweb ビューが表示されません。preferPrivateSession は内部で ASWebAuthenticationSession.prefersEphemeralWebBrowserSession を設定し、ユーザーの優先ブラウザがサポートしている場合、認証セッションはプライベートになります。
try await Amplify.Auth.signInWithWebUI( presentationAnchor: self.view.window!, options: .preferPrivateSession()) { ...}サインイン中の追加オプション
Amplify.Auth.signInWithWebUI に追加のパラメータを渡すことができます。これらは Cognitoの認可エンドポイント へのリクエストでクエリパラメータとして追加されます。
let options = AuthWebUISignInRequest.Options( pluginOptions: AWSAuthWebUISignInOptions.init( nonce: "randomUUID", language: "en", loginHint: "username", prompt: [.login, .consent], resource: "http://localhost"))
let signInResult = try await Amplify.Auth.signInWithWebUI( presentationAnchor: self.view.window!, options: options)