Page updated Jan 16, 2024

Set up Amplify Auth

The Amplify Auth category provides an interface for authenticating a user. Behind the scenes, it provides the necessary authorization to the other Amplify categories. It comes with default, built-in support for Amazon Cognito User Pool and Identity Pool. The Amplify CLI helps you create and configure the auth category with an authentication provider.

New: The Authenticator UI component for SwiftUI is now generally available!

Once you've gone through the steps below, you can use it to automatically add authentication capabilities to your application.

Goal

To setup and configure your application with Amplify Auth and go through a simple api to check the current auth session.

Prerequisites

An application with Amplify libraries integrated and a minimum target of any of the following:

  • iOS 13.0, using Xcode 14.1 or later.
  • macOS 10.15, using Xcode 14.1 or later.
  • tvOS 13.0, using Xcode 14.3 or later.
  • watchOS 9.0, using Xcode 14.3 or later.
  • visionOS 1.0, using Xcode 15 beta 2 or later. (Preview support - see below for more details.)

For a full example, please follow the project setup walkthrough.

visionOS support is currently in preview and can be used by targeting the visionos-preview branch. As new Xcode 15 beta versions are released, the branch will be updated with any necessary fixes on a best effort basis.

For more information on how to use the visionos-preview branch, see Platform Support.

To use Auth in a macOS project, you'll need to enable the Keychain Sharing capability. In Xcode, navigate to your application target > Signing & Capabilities > + Capability, then select Keychain Sharing.

This capability is required because Auth uses the Data Protection Keychain on macOS as a platform best practice. See TN3137: macOS keychain APIs and implementations for more information on how Keychain works on macOS and the Keychain Sharing entitlement.

For more information on adding capabilities to your application, see Xcode Capabilities.

Install Amplify Libraries

  1. To install Amplify Libraries in your application, open your project in Xcode and select File > Add Packages....

  2. Enter the Amplify Library for Swift GitHub repo URL (https://github.com/aws-amplify/amplify-swift) into the search bar and click Add Package.

Note: Up to Next Major Version should be selected from the Dependency Rule dropdown.

  1. Lastly, choose AWSCognitoAuthPlugin and Amplify. Then click Add Package.

Set Up Backend Resources

The most common way to use Authentication with Amplify is via the Amplify CLI, which allows you to create new Amazon Cognito resources or import existing ones. However, you can also use the Amplify Studio console to configure authentication or use the Amplify.configure() method to set up authentication with existing resources.

Prerequisites: Install and configure the Amplify CLI in addition to the Amplify libraries and necessary dependencies.

To start provisioning auth resources in the backend, go to your project directory and execute the command:

amplify add auth
1amplify add auth

Enter the following when prompted:

? Do you want to use the default authentication and security configuration? `Default configuration` ? How do you want users to be able to sign in? `Username` ? Do you want to configure advanced settings? `No, I am done.`
1? Do you want to use the default authentication and security configuration?
2 `Default configuration`
3? How do you want users to be able to sign in?
4 `Username`
5? Do you want to configure advanced settings?
6 `No, I am done.`

If you have previously enabled an Amplify category that uses Auth behind the scenes (e.g. API category), you can run the amplify update auth command to edit your configuration if needed.

To push your changes to the cloud, execute the command:

amplify push
1amplify push

Upon completion, amplifyconfiguration.json should be updated to reference provisioned backend auth resources. Note that these files should already be a part of your project if you followed the Project setup walkthrough.

Prerequisites: Install and configure the Amplify CLI in addition to the Amplify libraries and necessary dependencies.

To import existing Amazon Cognito resources into your Amplify project, execute the command:

amplify import auth
1amplify import auth
? What type of auth resource do you want to import? Cognito User Pool and Identity Pool Cognito User Pool only
1? What type of auth resource do you want to import?
2 Cognito User Pool and Identity Pool
3 Cognito User Pool only

Once you've selected an option, you'll be able to search for and import an existing Cognito User Pool and Identity Pool (or User Pool only) within your AWS account. The amplify import auth command will also do the following:

  • Automatically populate your Amplify Library configuration file (awsconfiguration.json) with your chosen Amazon Cognito resource information
  • Provide your designated existing Cognito resource as the authentication & authorization mechanism for all auth-dependent categories (API, Storage and more)
  • Enable Lambda functions to access the chosen Cognito resource if you permit it

If you have previously enabled an Amplify category that uses Auth behind the scenes (e.g. API category), you can run the amplify update auth command to edit your configuration if needed.

After configuring your Authentication options, update your backend and deploy the service by running the push command:

amplify push
1amplify push

Upon completion, amplifyconfiguration.json should be updated to reference provisioned backend auth resources.

Now, the authentication service has been deployed and you can start using it. To view the deployed services in your project at any time, go to Amplify Console by running the following command:

amplify console
1amplify console

For more details, see how to Use an existing Cognito User Pool and Identity Pool.

Prerequisites: Install and configure the Amplify CLI in addition to the Amplify libraries and necessary dependencies.

Amplify Studio allows you create auth resources, set up authorization rules, implement Multi-factor authentication (MFA), and more via an intuitive UI. To set up Authentication through the Amplify Studio, take the following steps:

  1. Sign in to the AWS Management Console and open AWS Amplify.
  2. In the navigation pane, choose an application.
  3. On the application information page, choose the Backend environments tab, then choose Launch Studio.
  4. On the Set up menu, choose Authentication.
  5. In the Configure log in section, choose a login mechanism to add from the Add login mechanism list. Valid options are Username, Phone number, Facebook, Google, Amazon, and Sign in with Apple. If you choose one of the social sign-in mechanisms (i.e. Facebook, Google, Amazon, or Sign in with Apple), you will also need to enter your App ID, App Secret, and redirect URLs.
  6. (Optional) Add multi-factor authentication (MFA). MFA is set to Off by default. To turn on MFA, do the following in the Multi-factor authentication section:
  • Choose Enforced to require MFA for all users or choose Optional to allow individual users to enable MFA.
  • (Optional) Choose SMS, and enter your SMS message.
  • (Optional) Choose Authenticator Application if you want your app to load with an authentication flow that includes sign up and sign in.
  1. In the Configure sign up section, expand Password protection settings and customize the password policy settings to enforce. u6. Choose Save and Deploy. This starts a CloudFormation deployment with the progress displayed in the upper right corner of the page.
  2. After creating and configuring your auth resources, you'll need to pull them down from Amplify Studio. To do so, simply click on "Local setup instructions" in the upper right hand corner of the Studio console and execute the CLI command it provides at the root directory of your app.

You can also import existing Amazon Cognito resources and manage users and groups through the Amplify Studio UI.

If you are not using the Amplify CLI, existing Authentication resources from AWS (e.g. Amazon Cognito UserPools or Identity Pools) can be used with the Amplify Libraries by manually creating a configuration file (amplifyconfiguration.json) and then updating the associated Plugin within it:

{ "auth": { "plugins": { "awsCognitoAuthPlugin": { "IdentityManager": { "Default": {} }, "CredentialsProvider": { "CognitoIdentity": { "Default": { "PoolId": "[COGNITO IDENTITY POOL ID]", "Region": "[REGION]" } } }, "CognitoUserPool": { "Default": { "PoolId": "[COGNITO USER POOL ID]", "AppClientId": "[COGNITO USER POOL APP CLIENT ID]", "Region": "[REGION]" } }, "Auth": { "Default": { "authenticationFlowType": "USER_SRP_AUTH", "socialProviders": [], "usernameAttributes": [], "signupAttributes": [ "[SIGNUP MECHANISM]" ], "passwordProtectionSettings": { "passwordPolicyMinLength": [PASSWORD LENGTH], "passwordPolicyCharacters": [] }, "mfaConfiguration": "OFF", "mfaTypes": [ "[MFA TYPE]" ], "verificationMechanisms": [ "[VERIFICATION MECHANISM]" ], "OAuth": { "WebDomain": "[YOUR COGNITO DOMAIN ]", "AppClientId": "[COGNITO USER POOL APP CLIENT ID]", "SignInRedirectURI": "[CUSTOM REDIRECT SCHEME AFTER SIGN IN, e.g. myapp://]", "SignOutRedirectURI": "[CUSTOM REDIRECT SCHEME AFTER SIGN OUT, e.g. myapp://]", "Scopes": [ "phone", "email", "openid", "profile", "aws.cognito.signin.user.admin" ] } } } } } } }
1{
2 "auth": {
3 "plugins": {
4 "awsCognitoAuthPlugin": {
5 "IdentityManager": {
6 "Default": {}
7 },
8 "CredentialsProvider": {
9 "CognitoIdentity": {
10 "Default": {
11 "PoolId": "[COGNITO IDENTITY POOL ID]",
12 "Region": "[REGION]"
13 }
14 }
15 },
16 "CognitoUserPool": {
17 "Default": {
18 "PoolId": "[COGNITO USER POOL ID]",
19 "AppClientId": "[COGNITO USER POOL APP CLIENT ID]",
20 "Region": "[REGION]"
21 }
22 },
23 "Auth": {
24 "Default": {
25 "authenticationFlowType": "USER_SRP_AUTH",
26 "socialProviders": [],
27 "usernameAttributes": [],
28 "signupAttributes": [
29 "[SIGNUP MECHANISM]"
30 ],
31 "passwordProtectionSettings": {
32 "passwordPolicyMinLength": [PASSWORD LENGTH],
33 "passwordPolicyCharacters": []
34 },
35 "mfaConfiguration": "OFF",
36 "mfaTypes": [
37 "[MFA TYPE]"
38 ],
39 "verificationMechanisms": [
40 "[VERIFICATION MECHANISM]"
41 ],
42 "OAuth": {
43 "WebDomain": "[YOUR COGNITO DOMAIN ]",
44 "AppClientId": "[COGNITO USER POOL APP CLIENT ID]",
45 "SignInRedirectURI": "[CUSTOM REDIRECT SCHEME AFTER SIGN IN, e.g. myapp://]",
46 "SignOutRedirectURI": "[CUSTOM REDIRECT SCHEME AFTER SIGN OUT, e.g. myapp://]",
47 "Scopes": [
48 "phone",
49 "email",
50 "openid",
51 "profile",
52 "aws.cognito.signin.user.admin"
53 ]
54 }
55 }
56 }
57 }
58 }
59 }
60}

For more information on Plugins, see the instructions on installing Amplify Libraries.

  • CredentialsProvider:
    • Cognito Identity:
      • Default:
        • PoolID: ID of the Amazon Cognito Identity Pool (e.g. us-east-1:123e4567-e89b-12d3-a456-426614174000)
        • Region: AWS Region where the resources are provisioned (e.g. us-east-1)
  • CognitoUserPool:
    • Default:
      • PoolId: ID of the Amazon Cognito User Pool (e.g. us-east-1_abcdefghi)
      • AppClientId: ID for the client used to authenticate against the user pool
      • Region: AWS Region where the resources are provisioned (e.g. us-east-1)
  • Auth:
    • Default:
      • authenticationFlowType: The authentication flow type, takes values USER_SRP_AUTH, CUSTOM_AUTH, and USER_PASSWORD_AUTH. Default is USER_SRP_AUTH.
      • OAuth: Hosted UI Configuration (only include this if using the Hosted UI flow)
        • Scopes: Scopes should match the scopes enables in Cognito under "App client settings"

If you are using a Cognito User Pool without a Cognito Identity Pool, you can omit the CredentialsProvider section in the configuration.

Initialize Amplify Auth

To initialize the Amplify Auth category, pass in the AWSCognitoAuthPlugin to Amplify.add(). When you are done calling add() on each category that you need, you finish configuring Amplify by calling Amplify.configure().

Add the following imports:

import Amplify import AWSCognitoAuthPlugin
1import Amplify
2import AWSCognitoAuthPlugin

Configure Amplify at app launch

Configure Amplify in the App init

@main struct MyAmplifyApp: App { var body: some Scene { WindowGroup { ContentView() } } init() { do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.configure() print("Amplify configured with auth plugin") } catch { print("Failed to initialize Amplify with \(error)") } } }
1@main
2struct MyAmplifyApp: App {
3
4 var body: some Scene {
5 WindowGroup {
6 ContentView()
7 }
8 }
9
10 init() {
11 do {
12 try Amplify.add(plugin: AWSCognitoAuthPlugin())
13 try Amplify.configure()
14 print("Amplify configured with auth plugin")
15 } catch {
16 print("Failed to initialize Amplify with \(error)")
17 }
18 }
19}

Add to your AppDelegate's application:didFinishLaunchingWithOptions method

func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.configure() print("Amplify configured with auth plugin") } catch { print("Failed to initialize Amplify with \(error)") } return true }
1func application(
2 _ application: UIApplication,
3 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
4) -> Bool {
5
6 do {
7 try Amplify.add(plugin: AWSCognitoAuthPlugin())
8 try Amplify.configure()
9 print("Amplify configured with auth plugin")
10 } catch {
11 print("Failed to initialize Amplify with \(error)")
12 }
13
14 return true
15}

Upon building and running this application you should see the following in your console window:

Amplify configured with auth plugin
1Amplify configured with auth plugin

Check the current auth session

You can now check the current auth session.

func fetchCurrentAuthSession() async { do { let session = try await Amplify.Auth.fetchAuthSession() print("Is user signed in - \(session.isSignedIn)") } catch let error as AuthError { print("Fetch session failed with error \(error)") } catch { print("Unexpected error: \(error)") } }
1func fetchCurrentAuthSession() async {
2 do {
3 let session = try await Amplify.Auth.fetchAuthSession()
4 print("Is user signed in - \(session.isSignedIn)")
5 } catch let error as AuthError {
6 print("Fetch session failed with error \(error)")
7 } catch {
8 print("Unexpected error: \(error)")
9 }
10}
func fetchCurrentAuthSession() -> AnyCancellable { Amplify.Publisher.create { try await Amplify.Auth.fetchAuthSession() }.sink { if case let .failure(authError) = $0 { print("Fetch session failed with error \(authError)") } } receiveValue: { session in print("Is user signed in - \(session.isSignedIn)") } }
1func fetchCurrentAuthSession() -> AnyCancellable {
2 Amplify.Publisher.create {
3 try await Amplify.Auth.fetchAuthSession()
4 }.sink {
5 if case let .failure(authError) = $0 {
6 print("Fetch session failed with error \(authError)")
7 }
8 }
9 receiveValue: { session in
10 print("Is user signed in - \(session.isSignedIn)")
11 }
12}

The isSignedIn property of the authSession will be false since you haven't signed in to the category yet.

Authentication with Amplify

There are two ways to add authentication capabilities to your application.

Option 1: Use the Authenticator UI component

Note: The Authenticator UI component is only available for SwiftUI.

The Authenticator is a UI component that automatically integrates with your existing Amplify configuration and allows you to easily add the entire authentication flow to your application.

Visit Authenticator | Amplify UI for Swift to get started.

Option 2: Manually call the Authentication APIs

Follow the instructions in Sign In to learn about how to integrate the registration and authentication flows in your application with the Auth APIs.

Next Steps

Congratulations! You've successfully setup AWS Cognito Auth plugin. Check out the following links to see other Amplify Auth use cases: