Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.
Gen1 DocsLegacy

Page updated Dec 10, 2024

IDトークンクレームのオーバーライド

defineAuthdefineFunction を使用して、Amazon Cognito Pre トークン生成 AWS Lambda トリガーを作成し、新しいクレームを追加するか、ユーザーのグループメンバーシップを変更することでトークンをオーバーライドできます。

まず、ハンドラータイプの定義に使用される aws-lambda パッケージをインストールしてください。

Terminal
npm add --save-dev @types/aws-lambda

新しいディレクトリとリソースファイル amplify/auth/pre-token-generation/resource.ts を作成します。次に、defineFunction で関数を定義します:

amplify/auth/pre-token-generation/resource.ts
import { defineFunction } from '@aws-amplify/backend';
export const preTokenGeneration = defineFunction({
name: 'pre-token-generation',
resourceGroupName: 'auth'
});

次に、対応するハンドラーファイル amplify/auth/post-confirmation/pre-token-generation/handler.ts を以下の内容で作成します:

amplify/auth/pre-token-generation/handler.ts
import type { PreTokenGenerationTriggerHandler } from "aws-lambda";
export const handler: PreTokenGenerationTriggerHandler = async (event) => {
event.response = {
claimsOverrideDetails: {
groupOverrideDetails: {
// This will add the user to the cognito group "amplify_group_1"
groupsToOverride: ["amplify_group_1"],
},
claimsToAddOrOverride: {
// This will add the custom claim "amplfy_attribute" to the id token
amplfy_attribute: "amplify_gen_2",
},
},
};
return event;
};

最後に、新しく作成した関数リソースを認証リソースに設定します:

amplify/auth/resource.ts
import { defineAuth } from '@aws-amplify/backend';
import { preTokenGeneration } from './pre-token-generation/resource';
export const auth = defineAuth({
loginWith: {
email: true,
},
triggers: {
preTokenGeneration
}
});

変更をデプロイした後、ユーザーの idToken は上記のトリガーに従って変更されます。

{
"cognito:groups": [
"amplify_group_1"
],
"email_verified": true,
"iss": "...",
"cognito:username": "...",
"origin_jti": "...",
"amplfy_attribute": "amplify_gen_2",
"aud": "...",
}