User group-based data access
You can use the group
authorization strategy to restrict access based on user groups. The user group authorization strategy allows restricting data access to specific user groups or groups defined dynamically on each data record.
Add authorization rules for specific user groups
When you want to restrict access to a specific set of user groups, provide the group names in the groups
parameter. In the example below, only users that are part of the "Admin" user group are granted access to the Salary model.
// allow one specific groupconst schema = a.schema({ Salary: a .model({ wage: a.float(), currency: a.string(), }) .authorization(allow => [allow.group('Admin')]),});
In your application, you can perform CRUD operations against the model with the userPools
auth mode.
try { final todo = Todo(content: 'My new todo'); final request = ModelMutations.create( todo, authorizationMode: APIAuthorizationType.userPools, ); final createdTodo = await Amplify.API.mutations(request: request).response;
if (createdTodo == null) { safePrint('errors: ${response.errors}'); return; } safePrint('Mutation result: ${createdTodo.name}');
} on APIException catch (e) { safePrint('Failed to create todo', e);}
This can then be updated to allow access to multiple defined groups; in this example below we added access for "Leadership".
// allow multiple specific groupsconst schema = a.schema({ Salary: a .model({ wage: a.float(), currency: a.string(), }) .authorization(allow => [allow.groups(['Admin', 'Leadership'])]),});
Add authorization rules for dynamically set user groups
With dynamic group authorization, each record contains an attribute specifying what Cognito groups should be able to access it. Use the first argument to specify which attribute in the underlying data store holds this group information. To specify that a single group should have access, use a field of type a.string()
. To specify that multiple groups should have access, use a field of type a.string().array()
.
// Dynamic group authorization with multiple groupsconst schema = a.schema({ Post: a .model({ title: a.string(), groups: a.string().array(), }) .authorization(allow => [allow.groupsDefinedIn('groups')]),});
// Dynamic group authorization with a single groupconst schema = a.schema({ Post: a .model({ title: a.string(), group: a.string(), }) .authorization(allow => [allow.groupDefinedIn('group')]),});
By default, group
authorization leverages Amazon Cognito user pool groups but you can also use OpenID Connect with group
authorization. See OpenID Connect as an authorization provider.