aws-amplify / amplify-js

A declarative JavaScript library for application development using cloud services.
https://docs.amplify.aws/lib/q/platform/js
Apache License 2.0
9.42k stars 2.12k forks source link

amazon-cognito-identity-js - Optional time buffer for CognitoUserSession.isValid #10956

Open jstarmx opened 1 year ago

jstarmx commented 1 year ago

Is this related to a new or existing framework?

No response

Is this related to a new or existing API?

Authentication

Is this related to another service?

No response

Describe the feature you'd like to request

This function detects if a session is valid - if not, it refreshes the ID and access tokens. https://github.com/aws-amplify/amplify-js/blob/main/packages/amazon-cognito-identity-js/src/CognitoUserSession.js#L73

If you are using these tokens to authenticate polling API requests, and especially if the expiry times of the tokens are short, on occasion the token will expire between the point that it is considered 'valid' and the point it is evaluated on the back-end.

This is a request to add an optional 'buffer' period, so that the tokens can be refreshed if they are within a certain time of expiry, e.g. 15 seconds, to prevent this issue from occurring.

Describe the solution you'd like

A way to define the buffer period, if not defined then existing behaviour is maintained.

Describe alternatives you've considered

Building an implementation outside of the library, but the library already takes care of things like debouncing multiple requests, so building it in would be a lot more efficient.

Additional context

Implementation could look something like

isValid() {
    const now = Math.floor(new Date() / 1000);
    const adjusted = now - this.clockDrift;

    const accessTokenExpiration = this.accessToken.getExpiration() - this.expiryBuffer;
    const idTokenExpiration = this.idToken.getExpiration() - this.expiryBuffer;

    return (
        adjusted < accessTokenExpiration &&
        adjusted < idTokenExpiration
    );
}

this.expiryBuffer would be set on initialisation, passed from config otherwise defaulting to 0.

Is this something that you'd be interested in working on?

haverchuck commented 3 months ago

Marked as a feature request.