You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Serverless中配置Cognito用户池的用户名+邮箱登录选项

解决Cognito用户池支持用户名+邮箱登录及注册的Serverless配置

核心配置思路

要实现同时支持用户名/邮箱登录,且注册时必填用户名、邮箱、密码,关键是两个CloudFormation属性的组合:

  • AliasAttributes: 指定可作为登录别名的属性(这里设为email,配合默认的用户名,实现双登录选项)
  • Schema: 强制邮箱为必填属性,确保注册表单显示该字段

不要使用UsernameAttributes: ['email'],这会将邮箱设为唯一的用户名标识,覆盖默认的用户名字段。

Serverless.yml 配置示例

在resources块中定义Cognito用户池及应用客户端:

resources:
  Resources:
    MyCognitoUserPool:
      Type: AWS::Cognito::UserPool
      Properties:
        UserPoolName: my-user-pool
        # 允许用邮箱作为登录别名,配合默认用户名实现双选项登录
        AliasAttributes:
          - email
        # 定义注册时的必填字段:用户名、邮箱、密码(密码默认必填)
        Schema:
          - Name: username
            AttributeDataType: String
            Mutable: true
            Required: true
            StringAttributeConstraints:
              MinLength: '3'
              MaxLength: '20'
          - Name: email
            AttributeDataType: String
            Mutable: true
            Required: true
            StringAttributeConstraints:
              MinLength: '5'
              MaxLength: '255'
            # 启用邮箱格式验证
            EmailVerificationMessage: "Your verification code is {####}"
            EmailVerificationSubject: "Verify your email"
        # 配置密码规则(可选,按需调整)
        Policies:
          PasswordPolicy:
            MinimumLength: 8
            RequireLowercase: true
            RequireUppercase: true
            RequireNumbers: true
            RequireSymbols: false

    MyCognitoUserPoolClient:
      Type: AWS::Cognito::UserPoolClient
      Properties:
        ClientName: my-app-client
        UserPoolId: !Ref MyCognitoUserPool
        # 启用托管UI的注册/登录功能
        SupportedIdentityProviders:
          - COGNITO
        CallbackURLs:
          - https://your-app-domain.com/callback
        LogoutURLs:
          - https://your-app-domain.com/logout
        AllowedOAuthFlows:
          - code
        AllowedOAuthScopes:
          - openid
          - email
          - profile
        # 确保客户端允许注册
        PreventUserExistenceErrors: ENABLED

配置说明

  1. AliasAttributes: 设置为email后,用户登录时可选择输入用户名或邮箱,Cognito会自动匹配对应的用户。
  2. Schema: 明确将username和email设为Required: true,这样托管UI的注册表单会自动显示这两个字段,配合默认的密码字段,满足注册时必填三项的要求。
  3. EmailVerification: 可选配置,启用邮箱验证确保用户提供的邮箱有效。
  4. UserPoolClient: 配置托管UI所需的OAuth参数,确保启用COGNITO作为身份提供商,支持注册流程。

配置完成后部署,托管UI的注册表单会显示用户名、邮箱、密码三个必填字段,登录时可输入用户名或邮箱进行验证。

内容的提问来源于stack exchange,提问作者Stretch0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 13:27:49