Accessing credentials
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 AWSPluginsCore2
3do {4 let session = try await Amplify.Auth.fetchAuthSession()5
6 // Get user sub or identity id7 if let identityProvider = session as? AuthCognitoIdentityProvider {8 let usersub = try identityProvider.getUserSub().get()9 let identityId = try identityProvider.getIdentityId().get()10 print("User sub - \(usersub) and identity id \(identityId)")11 }12
13 // Get AWS credentials14 if let awsCredentialsProvider = session as? AuthAWSCredentialsProvider {15 let credentials = try awsCredentialsProvider.getAWSCredentials().get()16 // Do something with the credentials17 }18
19 // Get cognito user pool token20 if let cognitoTokenProvider = session as? AuthCognitoTokensProvider {21 let tokens = try cognitoTokenProvider.getCognitoTokens().get()22 // Do something with the JWT tokens23 }24} catch let error as AuthError {25 print("Fetch auth session failed with error - \(error)")26} catch {27}
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 AWSPluginsCore2
3do {4 let session = try await Amplify.Auth.fetchAuthSession()5
6 // Get identity id7 if let identityProvider = session as? AuthCognitoIdentityProvider {8 let identityId = try identityProvider.getIdentityId().get()9 print("Identity id \(identityId)")10 }11
12 // Get AWS credentials13 if let awsCredentialsProvider = session as? AuthAWSCredentialsProvider {14 let credentials = try awsCredentialsProvider.getAWSCredentials().get()15 // Do something with the credentials16 }17} catch let error as AuthError {18 print("Fetch auth session failed with error - \(error)")19} catch {20 print("Unexpected error: \(error)")21}
Force refreshing session
You can ask the plugin to force refresh the internal session by passing an api options forceRefresh
while calling the fetchAuthSession api.
1Amplify.Auth.fetchAuthSession(options: .forceRefresh())