Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CognitoとAmplifyで爆速認証実装

 CognitoとAmplifyで爆速認証実装

More Decks by レバレジーズTechアカウント

Transcript

  1. Amplify Authで認証処理実装 ①Amplifyの初期化 Amplify.configure({ Auth: { region: "ap-northeast-1", userPoolId: "<USER_POOL_ID>",

    userPollWebClientId: "<CLIENT_ID>", // federatedSignInを使う場合 oauth: { domain: "<YOUR_DOMAIN>", scope: ["email", "openid", "aws.cognito.signin.user.admin"], redirectSignIn: "<URL_TO_REDIRECT_AFTER_SIGNIN>", redirectSignOut: "<URL_TO_REDIRECT_AFTER_SIGNOUT>", responseType: "code" } } }) _app.tsxで以下を実行する
  2. Amplify Authで認証処理実装 ②メールアドレスログインの実装 import { Auth } from "aws-amplify" const

    signInWithEmail = async (email, password) => { await Auth.signIn({ username: email, password: password, }) .then((response) => {}) .catch((error) => {}) } Auth.signInを実行するだけでOK
  3. Amplify Authで認証処理実装 ④セッション(jwt)の取得 AmplifyではlocalStorageもしくはcookieにjwtを自動で保持してくれるため currentSessionを呼び出すだけでセッション情報が取得可能 import { Auth } from

    "aws-amplify" const getAccessToken = async () => { const session = await Auth.currentSession() if (!session?.isValid()) { return null } return session.getAccessToken().getJwtToken() }
  4. Amplify Authとうまく付き合うTips ①アイデンティティプロバイダー認証後の処理はHub.listenで const signInWithGoogle = async () => {

    await Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Google, customState: "" }) .then((response) => { // ここに書いても動かない fetchUserFromOwnServer() }) } 例えばGoogleログインをするとリダイレクトするため thenやcatchで処理ができません
  5. Amplify Authとうまく付き合うTips ①アイデンティティプロバイダー認証後の処理はHub.listenで Hub.listen("auth", async ({ payload: { event, data

    } })) => { switch (event) { case "signIn": { // ここでアイデンティティプロバイダーで認証完了したことが検知できる fetchUserFromOwnServer() } } } なのでHub.listenで認証状態の変化を監視してあげるといいです
  6. Amplify Authとうまく付き合うTips ②アイデンティティプロバイダーの認証後のリダイレクト先を動的に変える Amplify.configure({ Auth: { // 省略 oauth: {

    // 省略 redirectSignIn: typeof window === "undefined" ? "固定値やenvから取得" : window.location.origin + window.location.pathname,, redirectSignOut: "<URL_TO_REDIRECT_AFTER_SIGNOUT>", responseType: "code" } } }) cognitoには複数のリダイレクトURLを設定できますが、Amplifyの設定ではできません。 登録ページとログインページのurlが分かれている場合などは動的にセットしてあげるといいです。
  7. Amplify Authとうまく付き合うTips ③アイデンティティプロバイダーの認証後に動的なパラメータを引き継ぐ Hub.listen("auth", async ({ payload: { event, data

    } })) => { switch (event) { case "customOAuthState": { const state = JSON.parse(data) // state.tokenと取れる } } } するとHub.listenでカスタムステートを取得することができます