Page updated Nov 3, 2023

Accessing credentials

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.

Amplify libraries should be used for all new cloud connected applications. If you are currently using the AWS Mobile SDK for iOS, you can access the documentation here.

An intentional decision with Amplify Auth was to avoid any public methods exposing credentials or manipulating them.

With Auth, you simply sign in and it handles everything else needed to keep the credentials up to date and vend them to the other categories.

However, if you need to access them in relation to working with an API outside Amplify or want access to AWS specific identifying information (e.g. IdentityId), you can access these implementation details by casting the result of fetchAuthSession as follows:

1import AWSPluginsCore
2
3Amplify.Auth.fetchAuthSession { result in
4 do {
5 let session = try result.get()
6
7 // Get user sub or identity id
8 if let identityProvider = session as? AuthCognitoIdentityProvider {
9 let usersub = try identityProvider.getUserSub().get()
10 let identityId = try identityProvider.getIdentityId().get()
11 print("User sub - \(usersub) and identity id \(identityId)")
12 }
13
14 // Get AWS credentials
15 if let awsCredentialsProvider = session as? AuthAWSCredentialsProvider {
16 let credentials = try awsCredentialsProvider.getAWSCredentials().get()
17 // Do something with the credentials
18 }
19
20 // Get cognito user pool token
21 if let cognitoTokenProvider = session as? AuthCognitoTokensProvider {
22 let tokens = try cognitoTokenProvider.getCognitoTokens().get()
23 // Do something with the Cognito tokens
24 }
25
26 } catch {
27 print("Fetch auth session failed with error - \(error)")
28 }
29}

If you have enabled guest user in Cognito Identity Pool and no user is signed in, you will be able to access only identityId and AWS credentials. All other session details will give you an error.

1import AWSPluginsCore
2
3Amplify.Auth.fetchAuthSession { result in
4 do {
5 let session = try result.get()
6
7 // Get identity id
8 if let identityProvider = session as? AuthCognitoIdentityProvider {
9 let identityId = try identityProvider.getIdentityId().get()
10 print("Identity id \(identityId)")
11 }
12
13 // Get AWS credentials
14 if let awsCredentialsProvider = session as? AuthAWSCredentialsProvider {
15 let credentials = try awsCredentialsProvider.getAWSCredentials().get()
16 // Do something with the credentials
17 }
18
19 } catch {
20 print("Fetch auth session failed with error - \(error)")
21 }
22}