AWS Amplify 身份验证问题:Next.js 项目中“未配置身份验证用户池”

问题描述 投票:0回答:1

我正在开发一个 NextJS 项目,其中使用 AWS Amplify 通过 Amazon Cognito 进行身份验证。但是,我遇到了一个问题,收到一条错误消息,指出 “未配置身份验证用户池” “当我尝试登录/注册时。我检查了我的配置,它们看起来是正确的,我还可以从AWS GUI手动创建用户。下面是相关代码和配置详细信息。

Index.js

import React, { useState, useEffect } from 'react'

import { Amplify } from 'aws-amplify'
import { Authenticator } from '@aws-amplify/ui-react'
import '@aws-amplify/ui-react/styles.css'
import { Auth } from 'aws-amplify'

Amplify.configure({
  Auth: {
    region: process.env.REGION,
    userPoolId: process.env.USER_POOL_ID,
    userPoolWebClientId: process.env.USER_POOL_APP_CLIENT_ID,
  },
})

function Home() {
  const [jwtToken, setJwtToken] = useState('')

  useEffect(() => {
    fetchJwtToken()
  }, [])

  const fetchJwtToken = async () => {
    try {
      const session = await Auth.currentSession()
      const token = session.getIdToken().getJwtToken()
      setJwtToken(token)
    } catch (error) {
      console.log('Error fetching JWT token:', error)
    }
  }

  return (
    <Authenticator
      initialState='signIn'
      components={{
        SignUp: {
          FormFields() {
            return (
              <>
                <Authenticator.SignUp.FormFields />

                {/* Custom fields for given_name and family_name */}
                <div>
                  <label>First name</label>
                </div>
                <input
                  type='text'
                  name='given_name'
                  placeholder='Please enter your first name'
                />
                <div>
                  <label>Last name</label>
                </div>
                <input
                  type='text'
                  name='family_name'
                  placeholder='Please enter your last name'
                />
                <div>
                  <label>Email</label>
                </div>
                <input
                  type='text'
                  name='email'
                  placeholder='Please enter a valid email'
                />
              </>
            )
          },
        },
      }}
      services={{
        async validateCustomSignUp(formData) {
          if (!formData.given_name) {
            return {
              given_name: 'First Name is required',
            }
          }
          if (!formData.family_name) {
            return {
              family_name: 'Last Name is required',
            }
          }
          if (!formData.email) {
            return {
              email: 'Email is required',
            }
          }
        },
      }}
    >
      {({ signOut, user }) => (
        <div>
          Welcome {user.username}
          <button onClick={signOut}>Sign out</button>
          <h4>Your JWT token:</h4>
          {jwtToken}
        </div>
      )}
    </Authenticator>
  )
}

export default Home

这是我使用

sam deploy --guided
运行的 template.yaml 文件来创建基础设施

AWSTemplateFormatVersion: 2010-09-09
Description: >-
  template for creating the Cognito User Pool
Transform:
  - AWS::Serverless-2016-10-31

Parameters:
  Env:
    Type: String
    Default: dev

  S3BucketName:
    Type: String
    Default: pibot-nextjs-website
  CognitoUserPoolName:
    Type: String
    Default: pibot-users-v2
  CognitoWebClientName:
    Type: String
    Default: cognito-webclient

Resources:
  CloudFrontOriginAccessIdentity:
    Type: 'AWS::CloudFront::CloudFrontOriginAccessIdentity'
    Properties:
      CloudFrontOriginAccessIdentityConfig:
        Comment: 'Origin Access Identity'

  CloudfrontDistribution:
    Type: 'AWS::CloudFront::Distribution'
    Properties:
      DistributionConfig:
        Comment: 'Cloudfront distribution for the static website'
        DefaultRootObject: 'index.html'
        Enabled: true
        HttpVersion: http2
        Origins:
          - Id: s3-website
            DomainName: !GetAtt S3Bucket.DomainName
            S3OriginConfig:
              OriginAccessIdentity:
                Fn::Sub: 'origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}'
        DefaultCacheBehavior:
          Compress: 'true'
          AllowedMethods:
            - GET
            - HEAD
            - OPTIONS
          ForwardedValues:
            QueryString: false
          TargetOriginId: s3-website
          ViewerProtocolPolicy: redirect-to-https

  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub '${Env}-${S3BucketName}'

  S3BucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref S3Bucket
      PolicyDocument:
        Statement:
          - Effect: Allow
            Action: 's3:GetObject'
            Resource:
              - !Sub 'arn:aws:s3:::${S3Bucket}/*'
            Principal:
              AWS: !Sub 'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${CloudFrontOriginAccessIdentity}'

  CognitoUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      UserPoolName: !Sub '${Env}-${CognitoUserPoolName}'
      AliasAttributes:
        - email
      UsernameConfiguration:
        CaseSensitive: false
      AutoVerifiedAttributes:
        - email
      Policies:
        PasswordPolicy:
          MinimumLength: 8
          RequireLowercase: true
          RequireNumbers: true
          RequireUppercase: true
          RequireSymbols: true
      Schema:
        - AttributeDataType: String
          Mutable: true
          Name: given_name
          Required: true
          StringAttributeConstraints:
            MinLength: '1'
        - AttributeDataType: String
          Mutable: true
          Name: family_name
          Required: true
          StringAttributeConstraints:
            MinLength: '1'
        - AttributeDataType: String
          Mutable: true
          Name: email
          Required: true
          StringAttributeConstraints:
            MinLength: '1'

  WebCognitoUserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    Properties:
      ClientName: !Sub '${Env}-${CognitoWebClientName}'
      UserPoolId: !Ref CognitoUserPool
      ExplicitAuthFlows:
        - ALLOW_USER_SRP_AUTH
        - ALLOW_REFRESH_TOKEN_AUTH
      PreventUserExistenceErrors: ENABLED

next.js amazon-cognito aws-amplify aws-sam
1个回答
0
投票

您需要使用

NEXT_PUBLIC_
作为您的环境变量,以使它们可以在您的浏览器环境中访问。 https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser

所以你的变量应该是:

Amplify.configure({
  region: process.env.NEXT_PUBLIC_REGION,
  userPoolId: process.env.NEXT_PUBLIC_USER_POOL_ID,
  userPoolWebClientId: process.env.NEXT_PUBLIC_USER_POOL_APP_CLIENT_ID,
});

也不要忘记更改 .env 文件中的 var 名称:)

© www.soinside.com 2019 - 2024. All rights reserved.