Page updated Nov 15, 2023

Set up Amplify Auth

Amplify iOS v1 is now in Maintenance Mode until May 31st, 2024. This means that we will continue to include updates to ensure compatibility with backend services and security. No new features will be introduced in v1.

Please use the latest version (v2) of Amplify Library for Swift to get started.

If you are currently using v1, follow these instructions to upgrade to v2.

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.

Goal

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

Prerequisites

  • An iOS application targeting at least iOS 11.0 with Amplify libraries integrated

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 iOS 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.

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 to the top of your AppDelegate.swift file:

import Amplify import AWSCognitoAuthPlugin
1import Amplify
2import AWSCognitoAuthPlugin

Add the following code

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

Then in the App scene, use UIApplicationDelegateAdaptor property wrapper to use your custom AppDelegate

@main struct MyAmplifyApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } }
1@main
2struct MyAmplifyApp: App {
3 @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
4
5 var body: some Scene {
6 WindowGroup {
7 ContentView()
8 }
9 }
10}

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() { _ = Amplify.Auth.fetchAuthSession { result in switch result { case .success(let session): print("Is user signed in - \(session.isSignedIn)") case .failure(let error): print("Fetch session failed with error \(error)") } } }
1func fetchCurrentAuthSession() {
2 _ = Amplify.Auth.fetchAuthSession { result in
3 switch result {
4 case .success(let session):
5 print("Is user signed in - \(session.isSignedIn)")
6 case .failure(let error):
7 print("Fetch session failed with error \(error)")
8 }
9 }
10}

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

Next Steps

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