0
0

aws-amplifyのAuthメソッドの使用方法の違い(v5以前とv6のバージョンを比較)

Last updated at Posted at 2024-09-08

Differences in Usage of Auth Methods in aws-amplify (Comparing Versions Prior to v5 and v6)

はじめに

amplifyのAuthメソッドについて、v5以前と最新のv6のバージョンで使用方法が異なる。
v5からv6でかなり破壊的な変更が入った。
ネットの記事はv5以前の書き方の使用例が多く、v5とv6の書き方の違いの代表例を2つ記載する。
他のメソッドにも大きな変更があったと思われるが、筆者が使用するうえではまった箇所を紹介する。

Amplify.configureのキー名の違い

※v5,v6を問わずaws-amplifyのAuthメソッドを使うためには、クライアントシークレットをOFFにしたアプリクライアントを使用する必要性があるため注意

v6の書き方
参考)https://docs.amplify.aws/gen1/react/tools/libraries/configure-categories/

v6
Amplify.configure({
  Auth: {
    Cognito: {
      region: "ap-northeast-1",
      userPoolId: "ap-northeast-1_aaaaaa",
      //アプリクライアントを設定するキー名がv5と異なり'userPoolClientId'
      userPoolClientId: "abcdabcd", // クライアントシークレットOFFのクライアント
    },
  },
});

v5の書き方
参考)https://docs.amplify.aws/gen1/react/prev/tools/libraries/configure-categories/

v5
Amplify.configure({
  Auth: {
    region: "ap-northeast-1",
    userPoolId: "ap-northeast-1_aaaaaa",
    //アプリクライアントを設定するキー名がv6と異なり'userPoolWebClientId'
    userPoolWebClientId: "abcdabcd", // クライアントシークレットOFFのクライアント
  },
});

signinの扱い

参考https://docs.amplify.aws/gen1/react-native/build-a-backend/troubleshooting/migrate-from-javascript-v5-to-v6/#auth

違い要約

  • 書き方以外にもレスポンスの内容や例外が返る条件にも変更があった。
  • ログイン済みユーザでログインした場合にUserAlreadyAuthenticatedException: There is already a signed in user.エラーが出るようになった。
  • 引数が (username, password)から({username, password})のオブジェクトになった。
  • v6でレスポンスに含まれる情報が大きく減った。
    • v5ではuserのsub等、後処理で使い得る情報が多く入っていた。
    • v6からはログイン済みかとNextActionしか返ってこなくなった。
      • subを使いたい場合、再fetchの必要あり。

v6

v6
const handleSignIn = async (username, password) => {
    try {
      // idTokenが存在する(サインイン済み)場合、サインアウトする
      const fetched = await fetchAuthSession();
      if (fetched.tokens.idToken) {
        console.log("fetched", fetched);
        await signOut();
      }
      
      // 引数がオブジェクトになっている
      const result = await signIn({ username, password });
      
      // v6からsignIn後のレスポンスにsubが入らないためsubが欲しいなら再度fetchする必要がある
      const fetchedResult = await fetchAuthSession();
    } catch (error) {
      console.log(error);
    }
  };

v5

v5
const handleSignIn = async (username, password) => {
    try {
      // 引数がオブジェクトじゃない
      const result = await Auth.signIn( username, password );

      // レスポンスにsub等の情報が多く含まれる
    } catch (error) {
      console.log(error);
    }
  };
0
0
0

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
0
0