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

如何通过Amplify Authenticator为注册用户设置Cognito自定义属性?

解决AWS Amplify Authenticator组件关联Marketplace客户ID到Cognito自定义属性的方案

方法1:自定义注册表单(最灵活可控)

先在Cognito用户池创建自定义属性(如custom:marketplaceCustomerId),然后完全自定义注册表单,直接通过Auth.signUp方法传递自定义属性:

import { Auth } from 'aws-amplify';
import { useState, useEffect } from 'react';

function CustomSignUp() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [marketplaceId, setMarketplaceId] = useState('');

  // 从URL重定向参数中提取Marketplace客户ID
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const id = params.get('customerId');
    if (id) setMarketplaceId(id);
  }, []);

  const handleSignUp = async (e) => {
    e.preventDefault();
    try {
      await Auth.signUp({
        username: email,
        password,
        attributes: {
          email,
          'custom:marketplaceCustomerId': marketplaceId // 传入自定义属性
        }
      });
      // 注册成功后的逻辑,比如跳转验证页
    } catch (error) {
      console.error('注册失败:', error);
    }
  };

  return (
    <form onSubmit={handleSignUp}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="邮箱"
        required
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="密码"
        required
      />
      {/* 隐藏字段,自动填充从URL获取的ID */}
      <input type="hidden" value={marketplaceId} />
      <button type="submit">注册</button>
    </form>
  );
}

export default CustomSignUp;

方法2:基于默认Authenticator组件扩展

如果想保留Amplify默认UI,可通过formFields添加隐藏字段,在onSubmit钩子中补充自定义属性:

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

function App() {
  const marketplaceId = new URLSearchParams(window.location.search).get('customerId');

  const handleSignUp = async ({ username, password, attributes }) => {
    try {
      const updatedAttrs = {
        ...attributes,
        'custom:marketplaceCustomerId': marketplaceId
      };
      return await Auth.signUp({ username, password, attributes: updatedAttrs });
    } catch (error) {
      throw error;
    }
  };

  return (
    <Authenticator
      signUpAttributes={['email']}
      formFields={[
        { type: 'email', label: '邮箱', required: true },
        { type: 'password', label: '密码', required: true },
        { type: 'hidden', name: 'marketplaceId', value: marketplaceId }
      ]}
      onSubmit={handleSignUp}
    >
      {({ signOut, user }) => (
        <div>
          <p>欢迎, {user.username}</p>
          <button onClick={signOut}>退出登录</button>
        </div>
      )}
    </Authenticator>
  );
}

export default App;

方法3:通过Post-Confirmation Lambda钩子补充数据

若前端无法直接传递,可在注册时通过clientMetadata传递数据,再用Cognito的Post-Confirmation Lambda钩子更新用户属性:

前端代码片段

await Auth.signUp({
  username: email,
  password,
  attributes: { email },
  clientMetadata: { marketplaceCustomerId: marketplaceId } // 传递元数据
});

Lambda函数代码(Node.js)

const AWS = require('aws-sdk');
const cognito = new AWS.CognitoIdentityServiceProvider();

exports.handler = async (event) => {
  const { userPoolId, userName, clientMetadata } = event;
  
  if (clientMetadata?.marketplaceCustomerId) {
    const params = {
      UserPoolId: userPoolId,
      Username: userName,
      UserAttributes: [
        {
          Name: 'custom:marketplaceCustomerId',
          Value: clientMetadata.marketplaceCustomerId
        }
      ]
    };
    
    try {
      await cognito.adminUpdateUserAttributes(params).promise();
    } catch (error) {
      console.error('更新自定义属性失败:', error);
    }
  }
  
  return event;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 16:05:06