Share
Embed
CognitoとAmplifyで爆速認証実装
Tech Leverages PRO
July 20, 2023
Transcript
25 slides
-
名前:田中紘夢(ひろむ) 出身:神奈川県横浜市 趣味:⚾🧖🏉🏖🍺 開発:TypeScript(React, Next.js, Nest.js)、趣味でFlutter 経歴 2021年3月 早稲田大学卒業 2021年4月
レバレジーズ新卒入社 2022年11月〜 オンライン診療事業に異動 -
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で以下を実行する -
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 -
Amplify Authで認証処理実装 ③Googleログイン(アイデンティティプロバイダーを使った認証) Auth.federatedSignInを実行する。成功するとconfigureに書いたurlにリダイレクト import { CognitoHostedUIIdentityProvider } from "@aws-amplify/auth"
import { Auth } from "aws-amplify" const signInWithGoogle = async () => { await Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Google, }) } -
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() } -
Amplify Authで認証処理実装 ⑤ログアウト Auth.signOutを呼び出すだけでOK アイデンティティプロバイダーのログインの場合はconfigureで指定したsignOutUrlにリダイレクト import { Auth } from
"aws-amplify" const signOut = () => Auth.signOut() -
Amplify Authとうまく付き合うTips ①アイデンティティプロバイダー認証後の処理はHub.listenで const signInWithGoogle = async () => {
await Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Google, customState: "" }) .then((response) => { // ここに書いても動かない fetchUserFromOwnServer() }) } 例えばGoogleログインをするとリダイレクトするため thenやcatchで処理ができません -
Amplify Authとうまく付き合うTips ①アイデンティティプロバイダー認証後の処理はHub.listenで Hub.listen("auth", async ({ payload: { event, data
} })) => { switch (event) { case "signIn": { // ここでアイデンティティプロバイダーで認証完了したことが検知できる fetchUserFromOwnServer() } } } なのでHub.listenで認証状態の変化を監視してあげるといいです -
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が分かれている場合などは動的にセットしてあげるといいです。 -
Amplify Authとうまく付き合うTips ③アイデンティティプロバイダーの認証後に動的なパラメータを引き継ぐ cognitoではリダイレクトURLのワイルドカードの指定ができないため、動的なパラメータがつく場 合などはカスタムステートで渡してあげる必要があります const signInWithGoogle = async ()
=> { await Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Google, customState: JSON.stringify({ token: "何かしらの動的パラメータなど" }) }) } -
Amplify Authとうまく付き合うTips ③アイデンティティプロバイダーの認証後に動的なパラメータを引き継ぐ Hub.listen("auth", async ({ payload: { event, data
} })) => { switch (event) { case "customOAuthState": { const state = JSON.parse(data) // state.tokenと取れる } } } するとHub.listenでカスタムステートを取得することができます