下一个选项是使用Next.js和aws-amplify auth(Cognito)进行用户身份验证
首先
-
- Next.js にCognitoによる認証機能を追加したときにやったことをメモしました。
- ほぼ自分用のメモ書きみたいな感じで、不備が多々あります、申し訳ありません。
版本
只摘录特别重要的内容。
-
- Next.js 13
-
- aws-amplify 6.0.5
- @aws-amplify/ui-react 6.0.3
"dependencies": {
"@aws-amplify/ui-react": "^6.0.3",
"@types/node": "20.5.9",
"@types/react": "18.2.21",
"aws-amplify": "^6.0.5",
"next": "13.4.19",
"react": "18.2.0",
},
添加身份验证功能的步骤
$ amplify init
$ amplify env list
$ amplify env checkout example
$ amplify push
→ Consoleでリソースができていることを確認
→ 認証機能追加
$ amplify env list (環境があっていることを確認)
$ amplify pull --appId xxxxxxxxxxxx --envName example (Consoleでコマンドを確認できる)
// 間違えてしまった場合
$ amplify env remove example
所需的IAM用户和角色
-
- IAM User: Amplifyの操作権限を持ったユーザー
-
- IAM Role:
Backendのデプロイ権限
Cognitoの操作権限
请留意以下事项
-
- コマンドに失敗しても、落ち着いてエラー文を読めば解決できることが多い。
特定のフォルダを削除するよう指示しているものがあった。
Console上で、Amplify Studio settingsの Enable OFF/ON を切り替えると直るものがあった。
Console上でフロントエンドのデプロイ設定を行う時は、必ずBackendのデプロイ権限を持たせたロールを設定する
请注意版本之间的差异
-
- 検索すると aws-amplifyのバージョンが5 の場合の記法が多くヒットするが、最新のバージョン6では、 Auth を書く必要がないなど、書き方が微妙に異なるので注意する→ 公式ドキュメント
以下、コード例
import '@/styles/globals.css'
import { Authenticator, View, Image, useTheme } from '@aws-amplify/ui-react'
import '@aws-amplify/ui-react/styles.css'
import { Amplify } from 'aws-amplify'
import type { AppProps } from 'next/app'
import React from 'react'
import awsExports from '@/aws-exports.js'
Amplify.configure(awsExports)
const authComponents = {
Header() {
const { tokens } = useTheme()
return (
<View textAlign='center' padding={tokens.space.xxxl}>
<Image alt='logo' src='/logo.png' />
</View>
)
},
}
export default function App({ Component, pageProps: { session, ...pageProps } }: AppProps) {
return (
// ユーザー登録を許可しない要件だったので、hideSignUp={true} を追加している
<Authenticator hideSignUp={true} components={authComponents}>
<Component {...pageProps} />
</Authenticator>
)
}
结束
- 不備が多々ありご迷惑をおかけします。適宜、他の記事と併せてお使いいただければ幸いです。