amplify-js: AWS Amplify gives invalid jwtToken after an hour

** Which Category is your question related to? ** AWS amplify auto handling refresh token ** What AWS Services are you utilizing? ** aws-amplify ** Provide additional details e.g. code snippets ** axios.interceptors.request.use(function(config) { return Auth.currentSession() .then(session => { // User is logged in. Set auth header on all requests let accessToken = session.idToken.jwtToken; axios.defaults.headers.common["Authorization"] = accessToken; return Promise.resolve(config); }) .catch(() => { // No logged-in user: don't set auth header return Promise.resolve(config); }); }); This is the interceptor request I’m using for now to get latest valid token irrespective of the total time, since user is logged-in as https://github.com/aws-amplify/amplify-js/issues/446 and aws-amplify documentation tells that it is automatically refreshing token internally and Auth.currentSession() gives you the latest valid jwtToken everytime. But what I experience is: I login: Auth.currentSession() keeps giving me the jwtToken that was received when logged_in. After an hour, the token was expired and Auth.currentSession() was still giving this previous expired token which caused my server to send me 401. How do I handle it? How do I keep getting latest valid refreshed jwtToken? Am I using it wrong or is it a bug or what? Please help ASAP! Posting this issue as suggested by @undefobj .

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 15 (1 by maintainers)

Most upvoted comments

I just figured out that Auth.currentSession() is giving latest valid token where the line axios.defaults.headers.common["Authorization"] = accessToken; was not setting latest token in request headers. I’ve resolved it by replacing this line with

          config.headers.common.Authorization = accessToken;

@matamicen Thanks a lot for your coordination and help!

@mghazanfar I don’t know Axios, so let’s do this in order to avoid bugs in your code, build a special async function just with the await Auth.currentSession() like this one:

refreshToken = async () => {
     var session = await Auth.currentSession();
     console.log("Refreshed token: " + session.idToken.jwtToken);
}

then call this function manually with a button (after the your token expires after one hour) and copy the generated token from the console and use an external program to call your API such as POSTMAN, so use the generated Token and see what is going on. (make sure to put the token in the Authorization parameter in the HEADER of POSTMAN).

What do you think about that?

Hope this helps.

@mghazanfar we are using session = await Auth.currentSession() without any problem. It refresh the token in the right way. Did you try the await way?