Amplify-js: Correct way of using currentSession

Created on 12 Apr 2018  路  17Comments  路  Source: aws-amplify/amplify-js

Do you want to request a feature or report a bug?
Feature

What is the current behavior?
When calling Auth.currentSession() after updating user attributes with Auth.updateUserAttributes, the current session wont have the updated user attributes. Is this the expected behavior?
If so, is there a way to update the current session without having to authenticate the user again?

And is the user session stored locally?

Which versions of Amplify, and which browser / OS are affected by this issue? Did this work in previous versions?

Version: aws-amplify": "^0.2.14

Auth documentation feature-request

Most helpful comment

@richardzcode
Looks like the JWT idToken does not get updated until it gets refreshed. Is there a way to manually trigger a JWT idToken refresh? This bug practically makes the idToken useless unless there is a way to refresh it after calling Auth.updateUserAttributes.

All 17 comments

@karlmosenbacher just wanted to confirm. What attributes are you trying to retrieve? Are you calling Auth.userAttributes(user) to get attributes?

@richardzcode After updating user attributes with Auth.updateUserAttributes I am trying to retrieve those updated attributes with Auth.currentSession. My thoughts was that the current session should also be updated with the latest user attributes changes, but they are not.

I haven't tried calling Auth.userAttributes because I thought that current session would be updated any time I call Auth.updateUserAttributes. So I am starting to wonder if I have misunderstood how the session work?

After Auth.updateUserAttributes, Auth.userAttributes always returns updated attributes.

Session object has some tokens, but not a source for user attributes. I'm guessing you are referring to idToken payload for user attributes?

Regarding the question at the top, and the README in Authentication - Retrieve current session, I am now unclear whether the Auth.currentSession()should return a promise or an object?

The doc shows it should returns an object but my current aws-amplify (0.3.3) do returns a promise.
Regardless, My main goal is to extract the idToken to then passing it into API headers for Cognito authorizer verification.
I could potentially wrap my API inside the promise but that means the documentation requires update, because accessing token via const { idToken } = Auth.currentSession()will be impossible. Would you kindly be able to shed some lights?

@edward-sia, Yes, it returns a promise. The doc sample needs to be updated. Thanks for pointing that out!

@richardzcode
Calling Auth.currentSession does not update the jwt id token. Restarting the app in the simulater does however give me the new token. Is there a way to refresh the jwt token after updating an attribute with Auth.updateUserAttributes?

@andidev
I'm facing the same issue. It will be nice if user attributes update after Auth.updateUserAttributes. That way I don't have to have run Auth.userAttributes(); along with Auth.currentSession() to get the current user's updated attributes every time user reload the page.

Auth.currentUserCredentials makes sure token is not expired, Auth.userAttributes gives most up-to-date attributes.

I will make an enhancement request to update token in currentSession after updateUserAttributes

@richardzcode
Looks like the JWT idToken does not get updated until it gets refreshed. Is there a way to manually trigger a JWT idToken refresh? This bug practically makes the idToken useless unless there is a way to refresh it after calling Auth.updateUserAttributes.

@mbahar As you have mentioned that the docs are wrong stating that currentSession() returns an object - is there a way to get the session synchronously, without awaiting the promise?

Are there any updates on this issue?

In our case, front-end is updating attributes however since id token doesn't get updated our backend is not aware of this change until user logs in again...

Well, after doing a lot of research, I figured it out, hope it helps all you guys with the same problem.
So it turned out that they have a function which I couldn't find it on their document being called "refreshSession", so if you use it in this order, it'll finally refresh your session:

`
import { Auth } from 'aws-amplify';

class AuthHelper {
static async refreshSessionPromise(refreshToken) {
return new Promise(async (resolve, reject) => {
const user = await Auth.currentAuthenticatedUser();
return user.refreshSession(refreshToken, async (err, data) => {
if (err)
reject(err);
else {
resolve(data); // THIS IS YOUR REFRESHED ATTRIBUTES/GROUPS
}
});
});
}
static async refreshCurrentSession() {
const session = await Auth.currentSession();
return await this.refreshSessionPromise(session.getRefreshToken());
}
}

export default AuthHelper;`

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Thanks @BardiaN this was a huge help! Formatted code below

import {
  Auth
} from 'aws-amplify';

class AuthHelper {
  static async refreshSessionPromise(refreshToken) {
    return new Promise(async (resolve, reject) => {
      const user = await Auth.currentAuthenticatedUser();
      return user.refreshSession(refreshToken, async (err, data) => {
        if (err) {
          reject(err);
        } else {
          resolve(data); // THIS IS YOUR REFRESHED ATTRIBUTES/GROUPS
        }
      });
    });
  }
  static async refreshCurrentSession() {
    const session = await Auth.currentSession();
    return this.refreshSessionPromise(session.getRefreshToken());
  }
}

export default AuthHelper;

Usage:

import { Auth } from 'aws-amplify'
import AuthHelper from '@/helpers/auth-helper'

async save() {
  const cognitoUser = this.$store.state.user
  if (!this.user || !cognitoUser) {
    return
  }
  try {
    await Auth.updateUserAttributes(cognitoUser, this.user)
    await AuthHelper.refreshCurrentSession()
  } catch (e) {
    console.log(e)
  }
}

I am using currentSession = await Auth.currentSession();.

But I am getting 401,{"message":"The incoming token has expired"}.

But the Auth.currentSession will automatically refresh the accessToken and idToken if tokens are expired and a valid refreshToken presented. So you can use this method to refresh the session if needed.

export async function get (endpoint: string, data?) {
    const currentSession = await Auth.currentSession();
    const providerId = currentSession.getIdToken().payload.sub;
    const identityJwt = currentSession.getIdToken().getJwtToken();
    return GET(endpoint, data, identityJwt, providerId);
}

I am using currentSession = await Auth.currentSession();.

But I am getting 401,{"message":"The incoming token has expired"}.

But the Auth.currentSession will automatically refresh the accessToken and idToken if tokens are expired and a valid refreshToken presented. So you can use this method to refresh the session if needed.

export async function get (endpoint: string, data?) {
    const currentSession = await Auth.currentSession();
    const providerId = currentSession.getIdToken().payload.sub;
    const identityJwt = currentSession.getIdToken().getJwtToken();
    return GET(endpoint, data, identityJwt, providerId);
}

I'm also facing this issue I want to refresh my expired token as mentioned in docs "This method will automatically refresh the accessToken and idToken if tokens are expired and a valid refreshToken presented. " but tokens are not refreshing

Closing, as this should have been addressed via #5394. Please let us know if your usage differs!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

guanzo picture guanzo  路  3Comments

TheRealRed7 picture TheRealRed7  路  3Comments

romainquellec picture romainquellec  路  3Comments

DougWoodCDS picture DougWoodCDS  路  3Comments

rayhaanq picture rayhaanq  路  3Comments