With admin actions
Amplify Auth can be managed with the AWS SDK's @aws-sdk/client-cognito-identity-provider
package. This package is intended to use server-side, and can be used within a Function. This example focuses on the addUserToGroup
action and will be defined as a custom mutation.
To get started, create an "ADMINS" group that will be used to authorize the mutation:
1import { defineAuth } from "@aws-amplify/backend"2
3export const auth = defineAuth({4 loginWith: {5 email: true,6 },8})
Next, create the Function resource:
1import { defineFunction } from "@aws-amplify/backend"2
3export const addUserToGroup = defineFunction({4 name: "add-user-to-group",5})
Then, in your auth resources, grant access for the function to perform the addUserToGroup
action. Learn more about granting access to auth resources.
1import { defineAuth } from "@aws-amplify/backend"3
4export const auth = defineAuth({5 loginWith: {6 email: true,7 },8 groups: ["ADMINS"],12})
You're now ready to define the custom mutation. Here you will use the newly-created addUserToGroup
function resource to handle the addUserToGroup
mutation. This mutation can only be called by a user in the "ADMINS" group.
1import type { ClientSchema } from "@aws-amplify/backend"2import { a, defineData } from "@aws-amplify/backend"3import { addUserToGroup } from "./resource"4
5const schema = a.schema({6 addUserToGroup: a7 .mutation()8 .arguments({9 userId: a.string().required(),10 groupName: a.string().required(),11 })12 .authorization((allow) => [allow.group("ADMINS")])13 .handler(a.handler.function(addUserToGroup))14 .returns(a.json())15})16
17export type Schema = ClientSchema<typeof schema>18
19export const data = defineData({20 schema,21 authorizationModes: {22 defaultAuthorizationMode: "iam",23 },24})
Lastly, create the function's handler using the exported client schema to type the handler function, and the generated env
to specify the user pool ID you'd like to interact with:
1import type { Schema } from "../resource"2import { env } from "$amplify/env/add-user-to-group"3import {4 AdminAddUserToGroupCommand,5 CognitoIdentityProviderClient,6} from "@aws-sdk/client-cognito-identity-provider"7
8type Handler = Schema["addUserToGroup"]["functionHandler"]9const client = new CognitoIdentityProviderClient()10
11export const handler: Handler = async (event) => {12 const { userId, groupName } = event.arguments13 const command = new AdminAddUserToGroupCommand({14 Username: userId,15 GroupName: groupName,16 UserPoolId: env.AMPLIFY_AUTH_USERPOOL_ID,17 })18 const response = await client.send(command)19 return response20}
In your frontend, use the generated client to call your mutation using the group name and the user's ID.
1import type { Schema } from "../amplify/data/resource"2import { generateClient } from "aws-amplify/data"3
4const client = generateClient<Schema>()5
6await client.mutations.addUserToGroup({7 groupName: "ADMINS",8 userId: "5468d468-4061-70ed-8870-45c766d26225",9})