Set up authorization rules
Amplify gives you the ability to limit which individuals or groups should have access to create, read, update, or delete data on your types by specifying an @auth
directive.
Here's a high-level overview of the authorization scenarios we support in the Amplify libraries. Each scenario has options you can tune to fit the needs of your application.
- Owner Based Authorization: Limit a model instance's access to an "owner" and defines authorization rules for those owners. Backed by Cognito User Pool.
- Static Group Authorization: Limit a model instance's access to a specific group of users and define authorization rules for that group. Backend by Cognito User Pool.
- Owner and Static Group Combined: Uses a combination of both Owner Based Authorization and Static Group Authorization to control ownership and access.
- Public Authorization: Allow public access to your model instances. Backed by an API Key or IAM.
- Private Authorization: Allow any signed-in user to access your model instances. Backed by IAM or Cognito User Pool.
- Owner based Authorization with OIDC provider: Use a 3rd party OIDC Provider to achieve Owner based authorization.
- Static Group Authorization with OIDC provider: Use a 3rd party OIDC Provider to achieve Static group authorization using a custom
groupClaim
.
Commonly used @auth
rule patterns
Per User / Owner Based Data Access
The following are commonly used patterns for owner based authorization. For more information on how to tune these examples, please see the CLI documentation on owner based authorization.
- Create/Read/Update/Delete mutations are private to the owner.
type YourModel @model @auth(rules: [{ allow: owner }]) { ...}
- Owners can create and delete; other signed-in users can read and update.
type YourModel @model @auth( rules: [ { allow: owner, operations: [create, delete] } { allow: private, operations: [read, update] } ] ) { ...}
Static Group Authorization
The following are commonly used patterns for static group authorization. For more information on how to tune these examples, please see the CLI documentation on static group authorization.
- Users belonging to the "Admin" group can CRUD (create, read, update, and delete), others cannot access anything.
type YourModel @model @auth(rules: [{ allow: groups, groups: ["Admin"] }]) { ...}
- Users belonging to the "Admin" group can create and delete, other signed users can read and update.
type YourModel @model @auth( rules: [ { allow: groups, groups: ["Admin"], operations: [create, delete] } { allow: private, operations: [read, update] } ] ) { ...}
Owner and Static Group Combined
The following are commonly used patterns for combining owner and static group authorization. For more information on how to tune these examples, please see the CLI documentation on static group authorization.
- Users have their own data, but users who belong to the
Admin
group have access to their data and anyone else in that group. Users in theAdmin
group have the ability to make mutation on behalf of users not in theAdmin
group
type YourModel @model @auth(rules: [{ allow: owner }, { allow: groups, groups: ["Admin"] }]) { ...}
Public Data Access
The following are commonly used patterns to grant everyone access. For more information on how to tune these examples, please see the CLI documentation on public data access.
- Auth provider is API Key
type YourModel @model @auth(rules: [{ allow: public }]) { ...}
- Auth provider is IAM
type YourModel @model @auth(rules: [{ allow: public, provider: iam }]) { ...}
Signed-in User Data Access
The following are commonly used patterns for private authorization. For more information on how to tune these examples, please see the CLI documentation on signed-in user data access.
- Cognito user pool authenticated users can CRUD all posts, regardless of who created it. Guest users do not have access.
type YourModel @model @auth(rules: [{ allow: private }]) { ...}
- IAM authenticated users can CRUD all posts, regardless of who created it. Guest users do not have access:
type YourModel @model @auth(rules: [{ allow: private, provider: iam }]) { ...}
Owner based Authorization with OIDC provider
The following are commonly used patterns for owner based authorization using a 3rd party OIDC provider (e.g. Facebook, Google, etc...). For more information on how to tune these examples, please see the CLI documentation on using an oidc authorization provider.
- Using a 3rd party OIDC provider to achieve owner based authorization.
type YourModel @model @auth(rules: [{ allow: owner, provider: oidc, identityClaim: "sub" }]) { ...}
When using a third-party OIDC auth provider, you are required to provide an instance of APIAuthProviderFactory
. Your factory implementation must be capable of creating objects conforming to the AmplifyOIDCAuthProvider
protocol. The responsibility of the AmplifyOIDCAuthProvider
is to return the JWT token that was provided by your OIDC provider. To do this:
- Create a subclass of
APIAuthProviderFactory
class MyAPIAuthProviderFactory: APIAuthProviderFactory { let myAuthProvider = MyOIDCAuthProvider()
override func oidcAuthProvider() -> AmplifyOIDCAuthProvider? { return myAuthProvider }}
- Implement your class which conforms to
AmplifyOIDCAuthProvider
:
class MyOIDCAuthProvider : AmplifyOIDCAuthProvider { func getLatestAuthToken() -> Result<String, Error> { .... }}
- Finally, register your instance of
APIAuthProviderFactory
prior to callingAmplify.configure()
:
let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels())try Amplify.add(plugin: dataStorePlugin)try Amplify.add(plugin: AWSAPIPlugin(apiAuthProviderFactory: MyAPIAuthProviderFactory()))try Amplify.configure()
Static Group Authorization with OIDC provider
The following are commonly used patterns for using groupClaims
to achieve group based authorization using a 3rd party OIDC provider. For more information on how to tune these examples, please see the CLI documentation on static group authorization.
- Using a custom value for
groupClaim
to achieve static group authorization with a 3rd party OIDC provider.
type YourModel @model @auth( rules: [ { allow: groups provider: oidc groups: ["Admin"] groupClaim: "https://myapp.com/claims/groups" } ] ) { ...}
Configure Multiple Authorization Types
For some use cases, you will want DataStore to use multiple authorization types. For example, an app might use API Key
for public content and Cognito User Pool
for personalized content once the user logs in.
By default, DataStore uses your API's default authorization type specified in the amplifyconfiguration.json
/.dart
/aws-exports.js
file. Every network request sent through DataStore uses that authorization type, regardless of the model's @auth
rule. To change the default authorization type, run amplify update api
.
To enable DataStore to use multiple authorization types based on the model's @auth
rules, run amplify update api
to configure additional auth types and deploy by running amplify push
. Then, configure the "auth mode strategy" when initializing DataStore:
Create a custom AppDelegate
, and add to your application:didFinishLaunchingWithOptions
method
class AppDelegate: NSObject, UIApplicationDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { do { let datastoreConfiguration = DataStoreConfiguration.custom(authModeStrategy: .multiAuth) let dataStorePlugin = AWSDataStorePlugin( modelRegistration: AmplifyModels(), configuration: datastoreConfiguration ) try Amplify.configure() print("Amplify configured with DataStore plugin") } catch { print("Failed to initialize Amplify with \(error)") return false }
return true }}
Then in the App
scene, use UIApplicationDelegateAdaptor
property wrapper to use your custom AppDelegate
@mainstruct MyAmplifyApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene { WindowGroup { ContentView() } }}
Add to your AppDelegate's application:didFinishLaunchingWithOptions
method
func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do { let datastoreConfiguration = DataStoreConfiguration.custom(authModeStrategy: .multiAuth) let dataStorePlugin = AWSDataStorePlugin( modelRegistration: AmplifyModels(), configuration: datastoreConfiguration ) try Amplify.configure() print("Amplify configured with DataStore plugin") } catch { print("Failed to initialize Amplify with \(error)") return false }
return true}
This configuration enables DataStore to synchronize data using the model's @auth
rule provider for each model.
Multiple authorization types priority order
If there are multiple @auth
rules on a model, the rules will be ranked by priority (see below), and DataStore will attempt the synchronization with each authorization type until one succeeds (or they all fail).
Priority | allow : AuthStrategy | provider |
---|---|---|
1 | owner | userPools |
2 | owner | oidc |
3 | group | userPools |
4 | group | oidc |
5 | private | userPools |
6 | private | iam |
7 | public | iam |
8 | public | apiKey |
If there is not an authenticated user session, DataStore will only attempt public
rules.
If a model has no auth rules defined, DataStore will continue to use the default authorization type from amplifyconfiguration.json
/.dart
.
Example with multiple authorization types
type YourModel @model @auth( rules: [ { allow: owner } { allow: public, provider: apiKey, operations: [read] } ] ) { ...}
DataStore will attempt to use owner-based authorization first when synchronizing data if there is an authenticated user. If that request fails for some reason, DataStore will attempt the request again with public authorization. If there is no authenticated user, public authorization will be used.