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:
1Future<void> fetchAuthSession() async {2 try {3 final result = await Amplify.Auth.fetchAuthSession(4 options: CognitoSessionOptions(getAWSCredentials: true),5 );6 String identityId = (result as CognitoAuthSession).identityId!;7 safePrint('identityId: $identityId');8 } on AuthException catch (e) {9 safePrint(e.message);10 }11}
If the getAWSCredentials
option is true, the result will contain AWS credentials and tokens. If it is set to false, the result will contain a simple isSignedIn
flag.
Setting a timeout for fetchAuthSession
On spotty networks, the fetchAuthSession
call can take upwards of a minute to either complete or fail due to internal retries. If this is too long, consider adding a custom timeout using the timeout
function as shown in the below example.
1Future<void> fetchAuthSessionWithTimeout() async {2 try {3 final result = await Amplify.Auth.fetchAuthSession().timeout(4 const Duration(seconds: 5),5 );6 final identityId = (result as CognitoAuthSession).identityId!;7 safePrint('identityId: $identityId');8 } on Exception catch (e) {9 safePrint('Something went wrong while fetching the session: $e');10 }11}