amazon-archives / amazon-cognito-auth-js

The Amazon Cognito Auth SDK for JavaScript simplifies adding sign-up, sign-in with user profile functionality to web apps.
Apache License 2.0
423 stars 232 forks source link

Unable to refresh token after access token expired #116

Open ovirta opened 6 years ago

ovirta commented 6 years ago

We are having hard time refreshing our tokens forcing clients to login after 1h.

We have AWS Cognito service in use for user authentication.

We have no problems getting a the access, ID and refresh tokens. They are saved in local storage and are fine (IMHO).

We are also able to renew tokens before expiration. But after access token is expired we are unable to refresh using the saved refresh token.

This is the function where we try to do the refresh:

   refreshToken(): Observable<any> {
    const options = {
      headers: new HttpHeaders({
        'Content-Type':  'application/x-www-form-urlencoded'
      })
    };
    let clientId: string = environment.clientIdSalesForce;
    let refreshToken: string = this.sessionKeyService.getRefreshToken();
    let body: any = `grant_type=refresh_token&client_id=${clientId}&refresh_token=${refreshToken}`;
    return this.httpClient.post(environment.tokenUrlSalesForce, body, options)
      .map((res: HttpResponse<any>) => res);
  }

curl: https://OUR_URL.eu-west-1.amazoncognito.com/oauth2/token

Body of the message: "grant_type=refresh_token&client_id=3i1t......glde&refresh_token=eyJjd.....uEW-OA"

Response: "Http failure response for https://OUR_URL.eu-west-1.amazoncognito.com/oauth2/token: 400 Bad Request"

Error: "invalid_client"

We don't have client_secret specified for the app.

Any insight what could go wrong in our scenario?

ovirta commented 6 years ago

Additional comment to the issue with refreshing tokens.

We are able to use above mentioned function to refresh tokens before access token has expired.

POST

header: 'Content-Type': 'application/x-www-form-urlencoded'
body: 'grant_type=refresh_token&client_id=${clientId}&refresh_token=${refreshToken}'

RESPONSE:

access_token:"eyJraWQi...B2iou_z...
expires_in:3600
id_token:"eyJraW...eXBlIjo
token_type:"Bearer"

Why is refresh succeeding before access token has expired?

tbpolicarpio commented 6 years ago

I dont know if this could help in your case. Maybe you could try using this: auth.refreshSession(refreshtoken);

I think this method creates the same request you're trying to do

chamathsilva commented 6 years ago

@tbpolicarpio You are right, it did the same thing and additionally it caches new tokens. (same as parseCognitoWebResponse() method)

ovirta commented 6 years ago

Thank you both for your responses. Will need to look into those.