11

Prior to every call made to the backend, I used Auth.currentAuthenticatedUser() to obtain idToken.jwtToken and pass it in the header of my request to the backend server for data.

Is there a difference between using Auth.currentSession() instead of Auth.currentAuthenticatedUser() for my use-case? Does Auth.currentAuthenticatedUser() refresh the token once it has expired, similar to Auth.currentSession()?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
user5735224
  • 461
  • 1
  • 7
  • 16

1 Answers1

7

The documentation for amplify auth is still very poor, so I looked into the source code for @aws-amplify/auth and amazon-cognito-identity-js packages and these are the findings:

  • currentAuthenticatedUser will try to retrieve authenticated user info from localstorage (unless your storage options is configured otherwise). If it doesn't exist in storage, then it will make api calls to retrieve user info which involves automatically refreshing the user session in the process.
  • currentSession will not check the local storage and always invoke the API which also involves automatically refreshing the user session if expired.

So to answer your question directly, the Auth.currentAuthenticatedUser() method doesn't always give you a valid token. If your storage contains an expired token, it will just return that. This would require you to call user.getSession() on the returned user object to request for a new session/token manually. I recommend that you use Auth.currentSession() since this handles the token refresh automatically and always returns a valid token.

hwkd
  • 2,411
  • 3
  • 18
  • 27
  • 2
    Amplify has updated their documentation regarding this: https://docs.amplify.aws/lib/auth/manageusers/q/platform/js#retrieve-current-session – hwkd Apr 15 '21 at 13:42
  • This explanation is still better than the docs! – mel Jul 30 '21 at 09:26