Use the @auth
directive to configure authorization rules for public, sign-in user, per user, and per user group data access. Authorization rules operate on the deny-by-default principle. Meaning that if an authorization rule is not specifically configured, it is denied.
In the example above, each signed-in user, or also known as "owner", of a Todo can create, read, update, and delete their own Todos.
Amplify also allows you to restrict the allowed operations, combine multiple authorization rules, and apply fine-grained field-level authorization.
In the example above, everyone (public
) can read every Todo but owner (authenticated users) can create, read, update, and delete their own Todos.
To help you get started, there's a global authorization rule defined when you create a new GraphQL schema. For production environments, remove the global authorization rule and apply rules on each model instead.
In the CDK construct, we call this the "sandbox mode" that you need to explicitly enable via an input parameter.
The global authorization rule (in this case { allow: public }
- allows anyone to create, read, update, and delete) is applied to every data model in the GraphQL schema.
Note: Amplify will always use the most specific authorization rule that's present. For example, a field-level authorization rule will be used in favor of a model-level authorization rule; similarly, a model-level authorization rule will be used in favor of a global authorization rule.
Currently, only { allow: public }
is supported as a global authorization rule.
Use the guide below to select the correct authorization strategy for your use case:
Public data accessTo grant everyone access, use the public
authorization strategy. Behind the scenes, the API will be protected with an API Key.
You can also override the authorization provider. In the example below, you can use an "Unauthenticated Role" from the Cognito identity pool for public access instead of an API Key.
When you run amplify add auth
, the Amplify CLI generates scoped down IAM policies for the "Unauthenticated role" in Cognito identity pool automatically.
Designate an Amazon Cognito identity pool's role for unauthenticated identities by setting the identityPoolConfig
property:
In the Amplify Library's client configuration file (amplifyconfiguration.json
) set allowGuestAccess
to true
. This lets the Amplify Library use the unauthenticated role from your Cognito identity pool when your user isn't logged in.
To restrict a record's access to a specific user, use the owner
authorization strategy. When owner
authorization is configured, only the record's owner
is allowed the specified operations.
Behind the scenes, Amplify will automatically add a owner: String
field to each record which contains the record owner's identity information upon record creation.
By default, the Cognito user pool's user information is populated into the owner
field. The value saved includes sub
and username
in the format <sub>::<username>
. The API will authorize against the full value of <sub>::<username>
or sub
/ username
separately and return username
. You can alternatively configure OpenID Connect as an authorization provider.
You can override the owner
field to your own preferred field, by specifying a custom ownerField
in the authorization rule.
Do not set ownerField
to your @primaryKey
field or id
field if no primary key is specified. If you want to query by the ownerField
, use an @index
on that ownerField
to create a secondary index.
By default, owners can reassign the owner of their existing record to another user.
To prevent an owner from reassigning their record to another user, protect the owner field (by default owner: String
) with a field-level authorization rule. For example, in a social media app, you would want to prevent Alice from being able to reassign Alice's Post to Bob.
If you want to grant a set of users access to a record, you can override the ownerField
to a list of owners. Use this if you want a dynamic set of users to have access to a record.
In the example above, upon record creation, the authors
list is populated with the creator of the record. The creator can then update the authors
field with additional users. Any user listed in the authors
field can access the record.
To restrict a record's access to every signed-in user, use the private
authorization strategy.
If you want to restrict a record's access to a specific user, see Per-user / owner-based data access.
private
authorization applies the authorization rule to every signed-in user access.
In the example above, anyone with a valid JWT token from Cognito user pool are allowed to access all Todos.
You can also override the authorization provider. In the example below, you can use an "Authenticated Role" from the Cognito identity pool for granting access to signed-in users.
When you run amplify add auth
, the Amplify CLI generates scoped down IAM policies for the "Authenticated role" in Cognito identity pool automatically.
Designate an Amazon Cognito identity pool role for authenticated identities by setting the identityPoolConfig
property:
In addition, you can also use OpenID Connect with private
authorization. See OpenID Connect as an authorization provider.
Note: If you have a connected child model that allows private
level access, any user authorized to fetch it from the parent model will be able to read the connected child model. For example,
In the above relationship, the owner of a Todo
record can query all the tasks connected to it, since the Task
model allows private
read access.
To restrict access based on user groups, use the group
authorization strategy.
Static group authorization: When you want to restrict access to a specific set of user groups, provide the group names in the groups
parameter.
In the example above, only users that are part of the "Admin" user group are granted access to the Salary model.
Dynamic group authorization: When you want to restrict access to a set of user groups.
With dynamic group authorization, each record contains an attribute specifying what Cognito groups should be able to access it. Use the groupsField
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 String
. To specify that multiple groups should have access, use a field of type [String]
.
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.
Known limitations for real-time subscriptions when using dynamic group authorization:
groups: [String]
example above),You can define your own custom authorization rule with a Lambda function.
The Lambda function of choice will receive an authorization token from the client and execute the desired authorization logic. The AppSync GraphQL API will receive a payload from Lambda after invocation to allow or deny the API call accordingly.
Configure the GraphQL API with the Lambda authorization mode, run the following command in your Terminal:
To configure a Lambda function as the authorization mode, set the lambdaConfig
in the CDK construct. Use the ttl
to designate the toke expiry time.
You can leverage this Lambda function code template as a starting point to author your authorization handler code:
You can use the default Amplify provided template as a starting point for your custom authorization rule. The authorization Lambda function receives:
Your Lambda authorization function needs to return the following JSON:
Review the Amplify Library documentation to set the custom authorization token for GraphQL API and DataStore.
Configure multiple authorization rulesWhen combining multiple authorization rules, they are "logically OR"-ed.
In the example above:
If you are using DataStore and have multiple authorization rules, you can let DataStore automatically determine the best authorization mode client-side. Review how to Configure Multiple Authorization Types on DataStore for more details.
Field-level authorization rulesWhen an authorization rule is added to a field, it'll strictly define the authorization rules applied on the field. Field-level authorization rules do not inherit model-level authorization rules. Meaning, only the specified field-level authorization rule is applied.
In the example above:
ssn
field. This field only has owner auth applied, the field-level auth rule means that model-level auth rules are not appliedTo prevent sensitive data from being sent over subscriptions, the GraphQL Transformer needs to alter the response of mutations for those fields by setting them to null. Therefore, to facilitate field-level authorization with subscriptions, you need to either apply field-level authorization rules to all required fields, make the other fields nullable, or disable subscriptions by setting it to public or off.
In the example above:
name
and email
fieldsssn
fieldTo prevent unintended loss of data, the user or role that attempts to delete
a record should have delete permissions on every field of the @model
annotated GraphQL type. For example, in the schema below:
Since the description
field is not accessible by "Admin" Cognito group users, they cannot delete any Todo
records.
Verify your API's access control matrix, by running the following command:
âââââââââââ¬âââââââââ¬âââââââ¬âââââââââ¬âââââââââ
â (index) â create â read â update â delete â
âââââââââââ¼âââââââââ¼âââââââ¼âââââââââ¼âââââââââ¤
â title â false â true â false â false â
â content â false â true â false â false â
âââââââââââ´âââââââââ´âââââââ´âââââââââ´âââââââââ
âââââââââââ¬âââââââââ¬âââââââ¬âââââââââ¬âââââââââ
â (index) â create â read â update â delete â
âââââââââââ¼âââââââââ¼âââââââ¼âââââââââ¼âââââââââ¤
â title â true â true â true â true â
â content â true â true â true â true â
âââââââââââ´âââââââââ´âââââââ´âââââââââ´âââââââââ
Use IAM authorization within the AppSync console
IAM-based @auth
rules are scoped down to only work with Amplify-generated IAM roles. To access the GraphQL API with IAM authorization within your AppSync console, you need to explicitly allow list the IAM user's name. Add the allow-listed IAM users by adding them to amplify/backend/api/<your-api-name>/custom-roles.json
. (Create the custom-roles.json
file if it doesn't exist). Append the adminRoleNames
array with the IAM role or user names:
To grant any IAM principal (AWS Resource, IAM role, IAM user, etc) access, with the exception of Amazon Cognito identity pool roles, to this GraphQL API in CDK, you need to enable IAM authorization mode via the iamConfig
property of the CDK construct.
These "Admin Roles" have special access privileges that are scoped based on their IAM policy instead of any particular @auth
rule.
These "Admin Roles" have special access privileges that are scoped based on their IAM policy instead of any particular @auth
rule.
private
, owner
, and group
authorization can be configured with an OpenID Connect (OIDC) authorization mode. Add provider: oidc
to the authorization rule.
Upon the next amplify push
, Amplify CLI prompts you for the OpenID Connect provider domain, Client ID, Issued at TTL, and Auth Time TTL.
Use the oidcConfig
property to configure the OpenID Connect provider domain, Client ID, Issued at TTL, and Auth Time TTL.
The example above highlights the supported authorization strategies with oidc
authorization provider. For owner
and group
authorization, you also need to specify a custom identity and group claim.
@auth
supports using custom claims if you do not wish to use the default Amazon Cognito-provided "cognito:groups" or the double-colon-delimited claims, "sub::username", from your JWT token. This can be helpful if you are using tokens from a 3rd party OIDC system or if you wish to populate a claim with a list of groups from an external system, such as when using a Pre Token Generation Lambda Trigger which reads from a database. To use custom claims specify identityClaim
or groupClaim
as appropriate like in the example below:
In this example the record owner will check against a user_id
claim. Similarly, if the user_groups
claim contains a "Moderator" string then access will be granted.
Lambda functions' IAM execution role do not immediately grant access to Amplify's GraphQL API because the API operates on a "deny-by-default"-basis. Access need to be explicitly granted. Depending on how your function is deployed, the workflow slightly differ
If you grant a Lambda function in your Amplify project access to the GraphQL API via amplify update function
, then the Lambda function's IAM execution role is allow-listed to honor the permissions granted on the Query
, Mutation
, and Subscription
types.
Therefore, these functions have special access privileges that are scoped based on their IAM policy instead of any particular @auth
rule.
Once you grant a function access to the GraphQL API, it is required to redeploy the API to apply the permissions. To do so, run the command amplify api gql-compile --force
before deployment via amplify push
.
To grant any IAM principal (AWS Resource, IAM role, IAM user, etc), with the exception of Amazon Cognito identity pool roles, to this GraphQL API in CDK, you need to enable IAM authorization mode on the CDK construct.
These "Admin Roles" have special access privileges that are scoped based on their IAM policy instead of any particular @auth
rule.
Refer to the sample code to learn how to sign the request to call the GraphQL API using IAM authorization.
Authorizing@manyToMany
relationships
Under the hood, the @manyToMany
directive will create a "join table" named after the relationName
to facilitate the many-to-many relationship. The authorization rules that Amplify applies to the "join table" it creates are a union of the authorization rules of the individual models in the many-to-many relationship.
For example, consider a schema in which the owner of a Post
(protected by an owner
rule) can apply Tag
s that are created by a system admin (protected by a groups
rule). Behind the scenes, Amplify creates a PostTags
table with both owner
and groups
auth:
For more control over the join table's authorization rules, you can create the join table explicitly, linking it to each model with a @hasMany
/@belongsTo
relationship, and set appropriate auth rules for your application.
Definition of the @auth
directive:
Authorization rules consists of:
allow
): who the authorization rule applies toprovider
): which mechanism is used to apply the authorization rule (API Key, IAM, Amazon Cognito user pool, OIDC)operations
): which operations are allowed for the given strategy and provider. If not specified, create
, read
, update
, and delete
operations are allowed.
read
operation: read
operation can be replaced with get
, list
, sync
, listen
, and search
for a more granular query accessIf you use DataStore instead of the API category to connect to your AppSync API, then you must allow listen
and sync
operations for your data model.
API Keys are best used for public APIs (or parts of your schema which you wish to be public) or prototyping, and you must specify the expiration time before deploying. IAM authorization uses Signature Version 4 to make request with policies attached to Roles. OIDC tokens provided by Amazon Cognito user pool or 3rd party OpenID Connect providers can also be used for authorization, and enabling this provides a simple access control requiring users to authenticate to be granted top level access to API actions.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4