Page updated Jan 16, 2024

Preview: AWS Amplify's new code-first DX (Gen 2)

The next generation of Amplify's backend building experience with a TypeScript-first DX.

Get started

Manage user session and credentials

Amplify Auth provides access to current user sessions and tokens to help you retrieve your user's information to determine if they are signed in with a valid session and control their access to your app. You can manage tokens and expiration times and revoke sessions. In this guide we will review how to retrieve your user’s session and understand what token management options are available.

Before you begin, you will need:

  • An Amplify project with the Auth category configured
  • The Amplify libraries installed and configured
  • A test user signed in

Retrieve your current authenticated user

You can use the getCurrentUser API to get information about the currently authenticated user including the username, userId and signInDetails.

1import { getCurrentUser } from 'aws-amplify/auth';
2
3async function currentAuthenticatedUser() {
4 try {
5 const { username, userId, signInDetails } = await getCurrentUser();
6 console.log(`The username: ${username}`);
7 console.log(`The userId: ${userId}`);
8 console.log(`The signInDetails: ${signInDetails}`);
9 } catch (err) {
10 console.log(err);
11 }
12}
1import { getCurrentUser } from 'aws-amplify/auth';
2
3async function currentAuthenticatedUser() {
4 try {
5 const { username, userId, signInDetails } = await getCurrentUser();
6 console.log(`The username: ${username}`);
7 console.log(`The userId: ${userId}`);
8 console.log(`The signInDetails: ${signInDetails}`);
9 } catch (err) {
10 console.log(err);
11 }
12}

This method can be used to check if a user is signed in. It throws an error if the user is not authenticated.

The user's signInDetails are not supported when using the Hosted UI or the signInWithRedirect API.

Retrieve a user session

Your user's session is their signed-in state, which grants them access to your app. When your users sign in, their credentials are exchanged for temporary access tokens. You can get session details to access these tokens and use this information to validate user access or perform actions unique to that user.

If you only need the session details, you can use the fetchAuthSession API which returns a tokens object containing the JWTs (JSON Web Tokens).

Learn more
Review what the tokens object contains and how tokens work

This secure information in the tokens object includes:

  • idToken - A JWT that contains user identity information like username and email. It is used to authenticate the user.
  • accessToken - A JWT used to access protected AWS resources and APIs. It contains the authorized scope.

Amazon Cognito tokens work by generating temporary access and ID tokens with an expiration time at user sign-in. The tokens are validated against the user pool to authorize access until they expire.

1import { fetchAuthSession } from 'aws-amplify/auth';
2
3async function currentSession() {
4 try {
5 const { accessToken, idToken } = (await fetchAuthSession()).tokens ?? {};
6 } catch (err) {
7 console.log(err);
8 }
9}
1import { fetchAuthSession } from 'aws-amplify/auth';
2
3async function currentSession() {
4 try {
5 const { accessToken, idToken } = (await fetchAuthSession()).tokens ?? {};
6 } catch (err) {
7 console.log(err);
8 }
9}

Refreshing sessions

The fetchAuthSession API automatically refreshes the user's session when the authentication tokens have expired and a valid refreshToken is present. Additionally, you can also refresh the session explicitly by calling the fetchAuthSession API with the forceRefresh flag enabled.

1import { fetchAuthSession } from 'aws-amplify/auth';
2
3async function currentSession() {
4 try {
5 const { tokens } = await fetchAuthSession({ forceRefresh: true });
6 console.log(tokens);
7 } catch (err) {
8 console.log(err);
9 }
10}

Refreshing sessions with social providers

To refresh the user's session when authenticating with a social provider, you need to use the code grant OAuth flow in your Amplify configuration.

1Amplify.configure({
2 Auth: {
3 Cognito: {
4 ...cognitoConfig,
5 loginWith: {
6 oauth: {
7 ...oauthConfig,
8 responseType: "code",
9 },
10 },
11 },
12 },
13})

Note: refreshing sessions with social providers will not work when the user has authenticated with a token OAuth flow, e.g { responseType: 'token' }.

Understand token management options

Token keys are automatically rotated for you for added security but you can update how they are stored, customize the refresh rate and expiration times, and revoke tokens on sign-out.

Update your token-saving mechanism

You can update the storage mechanism to choose where and how tokens are persisted in your application. The default option is localStorage. Additionally, you can import the sessionStorage, sharedInMemoryStorage or CookieStorage options as well.

If you want to customize your own mechanism, you can import the KeyValueStorageInterface interface and implement it in your own class.

Browser Local Storage

In Amplify the localStorage is the default storage mechanism. It saves the tokens in the browser's localStorage. This local storage will persist across browser sessions and tabs. You can explicitly set to this storage by calling:

1import { Amplify, type ResourcesConfig } from 'aws-amplify';
2import { defaultStorage } from 'aws-amplify/utils';
3import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
4
5const authConfig: ResourcesConfig['Auth'] = {
6 Cognito: {
7 userPoolId: 'your_user_pool_id',
8 userPoolClientId: 'your_user_pool_client_id'
9 }
10};
11
12Amplify.configure({
13 Auth: authConfig
14});
15
16cognitoUserPoolsTokenProvider.setKeyValueStorage(defaultStorage);
1import { Amplify } from 'aws-amplify';
2import { defaultStorage } from 'aws-amplify/utils';
3import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
4
5const authConfig = {
6 Cognito: {
7 userPoolId: 'your_user_pool_id',
8 userPoolClientId: 'your_user_pool_client_id'
9 }
10};
11
12Amplify.configure({
13 Auth: authConfig
14});
15
16cognitoUserPoolsTokenProvider.setKeyValueStorage(defaultStorage);

CookieStorage saves the tokens in the browser's Cookies. The cookies will persist across browser sessions and tabs. You can explicitly set to this storage by calling:

1import { Amplify, type ResourcesConfig } from 'aws-amplify';
2import { CookieStorage } from 'aws-amplify/utils';
3import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
4
5const authConfig: ResourcesConfig['Auth'] = {
6 Cognito: {
7 userPoolId: 'your_user_pool_id',
8 userPoolClientId: 'your_user_pool_client_id'
9 }
10};
11
12Amplify.configure({
13 Auth: authConfig
14});
15
16cognitoUserPoolsTokenProvider.setKeyValueStorage(new CookieStorage());
1import { Amplify } from 'aws-amplify';
2import { CookieStorage } from 'aws-amplify/utils';
3import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
4
5const authConfig = {
6 Cognito: {
7 userPoolId: 'your_user_pool_id',
8 userPoolClientId: 'your_user_pool_client_id'
9 }
10};
11
12Amplify.configure({
13 Auth: authConfig
14});
15
16cognitoUserPoolsTokenProvider.setKeyValueStorage(new CookieStorage());

Browser Session Storage

sessionStorage saves the tokens in the browser's sessionStorage and these tokens will clear when a tab is closed. The benefit to this storage mechanism is that the session only lasts as long as the browser is open and you can sign out users when they close the tab. You can update to this storage by calling:

1import { Amplify, type ResourcesConfig } from 'aws-amplify';
2import { sessionStorage } from 'aws-amplify/utils';
3import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
4
5const authConfig: ResourcesConfig['Auth'] = {
6 Cognito: {
7 userPoolId: 'your_user_pool_id',
8 userPoolClientId: 'your_user_pool_client_id'
9 }
10};
11
12Amplify.configure({
13 Auth: authConfig
14});
15
16cognitoUserPoolsTokenProvider.setKeyValueStorage(sessionStorage);
1import { Amplify } from 'aws-amplify';
2import { sessionStorage } from 'aws-amplify/utils';
3import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
4
5const authConfig = {
6 Cognito: {
7 userPoolId: 'your_user_pool_id',
8 userPoolClientId: 'your_user_pool_client_id'
9 }
10};
11
12Amplify.configure({
13 Auth: authConfig
14});
15
16cognitoUserPoolsTokenProvider.setKeyValueStorage(sessionStorage);

Custom Storage

You can implement your own custom storage mechanism by creating a class that implements the storage interface. Here is an example that uses memory storage:

1import { Amplify, type ResourcesConfig } from 'aws-amplify';
2import { KeyValueStorageInterface } from 'aws-amplify/utils';
3import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
4
5const authConfig: ResourcesConfig['Auth'] = {
6 Cognito: {
7 userPoolId: 'your_user_pool_id',
8 userPoolClientId: 'your_user_pool_client_id'
9 }
10};
11
12class MyCustomStorage implements KeyValueStorageInterface {
13 storageObject: Record<string, string> = {};
14 async setItem(key: string, value: string): Promise<void> {
15 this.storageObject[key] = value;
16 }
17 async getItem(key: string): Promise<string | null> {
18 return this.storageObject[key];
19 }
20 async removeItem(key: string): Promise<void> {
21 delete this.storageObject[key];
22 }
23 async clear(): Promise<void> {
24 this.storageObject = {};
25 }
26}
27
28Amplify.configure({
29 Auth: authConfig
30});
31
32cognitoUserPoolsTokenProvider.setKeyValueStorage(new MyCustomStorage());
1import { Amplify } from 'aws-amplify';
2import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
3
4const authConfig = {
5 Cognito: {
6 userPoolId: 'your_user_pool_id',
7 userPoolClientId: 'your_user_pool_client_id'
8 }
9};
10
11class MyCustomStorage {
12 storageObject = {};
13 async setItem(key, value) {
14 this.storageObject[key] = value;
15 }
16 async getItem(key) {
17 return this.storageObject[key];
18 }
19 async removeItem(key) {
20 delete this.storageObject[key];
21 }
22 async clear() {
23 this.storageObject = {};
24 }
25}
26
27Amplify.configure({
28 Auth: authConfig
29});
30
31cognitoUserPoolsTokenProvider.setKeyValueStorage(new MyCustomStorage());

When you get the current user session, the tokens will be saved in your custom location.

Note: You can also update token expiration times depending on how you configured your Amazon Cognito User Pool. If you used the Amplify CLI, you can run amplify update auth to do so. If not, you can also go through the Amazon Cognito User Pool console under App integration > App client settings or update the appropriate parameters via the AWS CLI or CDK.

Revoke tokens

Token revocation is enabled by default in new Cognito User Pool Clients, however, if you are using an existing client, you may need to enable it. This allows for all access tokens that were previously issued by that refresh token to become invalid.

To revoke tokens you can set up global sign-out with signOut({ global: true }) to globally sign out your user from all of their devices.

You can now change the user experience for your app by updating how and where your tokens are saved and managed.

Conclusion

Congratulations! You finished the Manage user session and credentials guide. In this guide, you learned how to retrieve you current authenticated user, the user's session details, and reviewed several ways you can manage these user credentials.

Next steps

Now that you updated how your credentials are managed you may also want to further refine the sing-in and sign-out workflows as well as update how you listen for these Auth events. We recommend you learn more about: