Published on

Resolved AuthError generated by Amplify(Cognito).

Authors

Cognito を用いた認証実装を行う中で AuthError が発生したのでその解決方法のまとめです。

結論

  • Amplify.configure() 実行のタイミングの問題

前提

  • Amplify は導入せず、Cognito だけ使用(ライブラリ aws-amplify は使用)
  • React 17.0.2
  • TypeScript 4.6.2
  • aws-amplify 4.3.2
  • aws-sdk 2.1119.0

内容

[ERROR] 07:00.214 AuthError - 
            Error: Amplify has not been configured correctly. 
            The configuration object is missing required auth properties.
            This error is typically caused by one of the following scenarios:

            1. Did you run `amplify push` after adding auth via `amplify add auth`?
                See https://aws-amplify.github.io/docs/js/authentication#amplify-project-setup for more information

            2. This could also be caused by multiple conflicting versions of amplify packages, see (https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js) for help upgrading Amplify packages.

Cognito を利用するため aws-amplify 等を利用するコードを実装したところ、上記のエラーがコンソールに吐かれるようになりました。

想定シナリオとして2つあげられていますが、今回は aws-amplify は利用するもののサービスとしての Amplify 自体は利用しない+複数のバージョンを入れているなどもないため当てはまらず。

結論としては、そもそもメッセージの初めの方に書かれている Error: Amplify has not been configured correctly. の問題でした(シナリオのほうに気を取られちゃってました)

Amplify.configure() が正しいタイミングで実行されていないことで、設定が正しく行われていないことが原因だったようです。

今回は認証周りを Context を用いて管理するようにしていますが、それを管理する Provider 内で呼び出すようにすることで解消しました。

// 今回は別で AWS 周りの設定定義しているのでモジュールを import
import { AwsConfigAuth } from '@config/aws'

export const AuthProvider = ({ children }: AuthProviderType) => {
  Amplify.configure({ Auth: AwsConfigAuth })

  const [state, dispatch] = useReducer(authReducer, defaultAuthState)

  return (
    <AuthStateContext.Provider value={state}>
      <AuthDispatchContext.Provider value={dispatch}>{children}</AuthDispatchContext.Provider>
    </AuthStateContext.Provider>
  )
}