Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Feb 21, 2024

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:

import AWSPluginsCore
do {
let session = try await Amplify.Auth.fetchAuthSession()
// Get user sub or identity id
if let identityProvider = session as? AuthCognitoIdentityProvider {
let usersub = try identityProvider.getUserSub().get()
let identityId = try identityProvider.getIdentityId().get()
print("User sub - \(usersub) and identity id \(identityId)")
}
// Get AWS credentials
if let awsCredentialsProvider = session as? AuthAWSCredentialsProvider {
let credentials = try awsCredentialsProvider.getAWSCredentials().get()
// Do something with the credentials
}
// Get cognito user pool token
if let cognitoTokenProvider = session as? AuthCognitoTokensProvider {
let tokens = try cognitoTokenProvider.getCognitoTokens().get()
// Do something with the JWT tokens
}
} catch let error as AuthError {
print("Fetch auth session failed with error - \(error)")
} catch {
}

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.

import AWSPluginsCore
do {
let session = try await Amplify.Auth.fetchAuthSession()
// Get identity id
if let identityProvider = session as? AuthCognitoIdentityProvider {
let identityId = try identityProvider.getIdentityId().get()
print("Identity id \(identityId)")
}
// Get AWS credentials
if let awsCredentialsProvider = session as? AuthAWSCredentialsProvider {
let credentials = try awsCredentialsProvider.getAWSCredentials().get()
// Do something with the credentials
}
} catch let error as AuthError {
print("Fetch auth session failed with error - \(error)")
} catch {
print("Unexpected error: \(error)")
}

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.

Amplify.Auth.fetchAuthSession(options: .forceRefresh())