OCAPI: How to refresh token after expiration? - jwt

Trying to use Salesforce OCAPI from an app.
On the JWT Auth documentation: https://documentation.b2c.commercecloud.salesforce.com/DOC2/index.jsp?topic=%2Fcom.demandware.dochelp%2FOCAPI%2Fcurrent%2Fusage%2FJWT.html
A JWT has a lifetime of 30 minutes. Before the token expires, you must exchange it for a new token if you want to extend the total lifetime.
If a registered user opens the app after 31 minutes and the persisted JWT is expired, then how is the way to refresh it without prompting login screen again? (persisting user credentials is out of the question due to security vulnerability)

As the documentation states, you cannot refresh it if it has expired. You must prompt for the login screen again.
I suggest having your app refresh the token automatically in the background.

You can save exp (the token expiration-time) from payload section in your db, try to check before intiatling new call if its expire then you can use the /customers/auth resource to get new token. You must include the current token in the Authentication:Bearer request header, and specify the customer type as "type":"refresh".

Related

Refresh token refresh rate

Let's say we have a refresh token with a lifetime of a month. Within that month with each subsequent call to the "auth" endpoint(with username and password) should the same refresh token be returned, or should a new one be generated, and why?
Long story short...should the user be forced to log in again after the lifetime of the refresh token expires, or should he be allowed to refresh his tokens indefinitely?
The usual pattern I have seen used is that the initial authentication or refresh call is what would return both a new access token and a new refresh token. One use of the refresh token is for acquiring a new access token after the current/old access token has expired. Here is an example workflow:
user authenticates via 1FA/2FA to the server
access and refresh tokens are returned; refresh token lives slightly longer than access token, by design
after some time, the access token expires, and the user sends the refresh token to the server
a new access and refresh token are returned, continue from the second step above
As the refresh token intentionally will outlive the access token, there is no need to send a new refresh token with each request. Rather, simply let the user initiate the request for a new access/refresh token when the time comes.

JWT access token in-memory?

I’ve been spending hours and hours on this, this is the first time I am using JWT and would really need some of your thougts.
Right now I store my tokens in separate httpOnly cookies (my access token expires after 15 min and refresh token after 7 days).
I have read that the most secure way to store the tokens is actually using a cookie for the refresh token and in-memory (like in a variable) for the access token.
While I understand this is secure, I do not really understand how it would work in practice. Would it mean that we have to create a new access token with our refresh token on each request? Or is there a way we can make it valid and copied to new variables until it is expired?
I am using react and node btw.
I spent days reading about this too.
From what I gathered a solution would be something like this:
User logs in with login and password.
Server generates a refresh token long lived to be stored as an HttpOnly Cookie, preventing XSS attacks as it can not be accessed by Javascript.
Ideally some sort of blacklist can be used server-side to prevent re-use of refresh tokens that have not reached their expiry but have been replaced.
Generate an access token which can either be stored in localStorage or in-memory (in a variable). The access token has a short expiry life of a few minutes.
If stored in localStorage, the token will not disappear on a reload of the page/browser (F5). It will also be visible in the console/storage.
When using localStorage to check if user is authenticated, the code will try to read the token from localStorage, jwt_decode it and set a user variable with the data that is in the token.
As tokens are not encrypted, just base64, their values can be changed in the dev console. A page that is "role: admin" only will be rendered if the permission is changed. The API will be responsible to check for permissions and reject the request if the token has been tampered.
Afaik, if it is stored in a variable it is a little less visible, it also gets wiped when reloading the page/browser.
When using a variable, to avoid refreshing the access token on every request, we can use the Context API, by creating a Component with the authenticated user context that will wrap the App/Router and then on every page that needs to be protected import and use this context and redirect if needed.
When the access token is not valid anymore, because it has reached its expiry, or because it has been wiped, the API call will get rejected. Intercept this call then call the API refresh route to use the refresh token to generate a new access token.
I use axios with axios interceptor to intercept the failed request, call the refresh route, set the renewed access token, then retry the failed request. (needs to be a GET request to avoid CSRF errors apparently).
In addition (not in place of), a setTimeout can be used to automatically refresh the access token every X minutes to prevent letting it expire.
To log out, remove the cookie (eventually blacklist) and wipe the context / localStorage.
Using axios, axios.defaults.withCredentials = true; makes sure that the cookie is sent with the requests and { headers: { 'Authorization': `Bearer ${access_token}` } } makes sure the access "bearer" token is sent with the request. These can either be set as defaults for every request or per request hence these 2 syntaxes.
Github example with Flask and React

Does I understand access and refresh token technique for authentication correctly?

After doing some research in using JWT with Access Token and Refresh Token for authentication. I understand this in this way.
After login, return to user Access Token and Refresh Token (using same technique JWT for both).
Saving Refresh Token in Database (one User can have multiple Refresh Tokens for multiple devices).
Whenever user sends a request with invalid Access Token, check Refresh Token and call another api to get new Access Token (doing this in client side). After that, call api to get data again with new Access Token.
If Refresh Token is invalid, deleting its record in database and user must to login again to get new Refresh Token.
Does I understand Access and Refresh Token technique correctly? Please give me some advices. Thank in advance.
Of the 4 steps you listed, some look more or less correct while others do not. I will begin this answer by giving the premise for why refresh tokens were created and what is their main purpose.
Using the JWT pattern with only access tokens, there is a potential usability problem when the JWT token expires. Consider as an example a banking website. When a user logs in, he receives a JWT token with a certain expiry (typically stored under the exp key in the claims section of the token). If the token is given say a 5 minute expiry, then from a usability point of view, it means that the website would have to force the user to manually login every 5 minutes. Obviously, this is not the best user experience, because it means that a user who happens to be in the middle of some business process when the token expires might lose all that work. This is where refresh tokens step in to alleviate this problem.
Using the JWT pattern with refresh tokens means that the user receives both an access and a refresh token. A typical workflow here might be:
After login, return to user Access Token and Refresh Token (using same technique JWT for both). The receiver notes when the access token is set to expire (say 15 minutes).
As the expiry of the access token approaches (e.g. 10 minutes), the UI will send the refresh token to the backend to obtain a new access token (and refresh token). This could be done explicitly, e.g. on a website which displays a popup asking if the user wants to continue. Or it could be done in stealth mode, with a REST call being made under the hood to get the new access token.
For the edge case where the refresh token cannot be used to obtain a new access token, then the very next user action which requires authentication would fail. In this case, the user would have to redirected to the login page. But, as this case should generally be rare, it does not disqualify the refresh token pattern.
I would also point out that storing the access/refresh tokens in the database largely defeats the purpose of the JWT pattern. One major reason for using JWT is that it pushes the user session state out of the application and onto the user. By storing tokens in your database, you are totally making your user sessions very stateful, which has all sorts of potential drawbacks. Consider using the suggested workflow above to avoid doing this.
The way I see it, your refresh token needs to be stored and associated with the device and the user.
Example:
User Logs In in Device A
Call Login endpoint
Validate user is valid
If valid, generate a refresh token associated with the userid & device
id
store required data to your table or storage engine (user_sessions..etc)
user_id | device_id | refresh_token | expires_at
Return the payload with access_token, refresh_token , access_token_expires_at, refresh_token_expires_at
Front-end, store the payload
when consuming a resource, check the following
If refresh_token_expires_at > now then logs them out , show your session is timeout (or you can have a never expired refresh_token.. ex. refresh_token_expires_at can be 0)
if access_token_expires_at > now then call refresh token endpoint along with your payload.
on the refresh endpoint, validate the call and check the refresh token against the data stored.
if refresh token is valid for this user+device, generate a new access_token
return the access_token and its expires_at
If the refresh token is INvalid , return invalid
front end will log the user out.
** in any case, if a refresh token was compromised, it will be only for that particular device/user. A user can then deactivate or remove the device from their list. This action will invalidate the refresh_token on their next refresh call.

How to extend token expiring time if user is not active for a set period using JWT?

Given an example here for a normal web app.
Traditionally, we use session and set timeout = 30 minutes. if session expires we will redirect user to login. (Expired time will be extended when user/browser interact with web app)
Using JWT, how to achieve that?
I know something about "token refresh", when short-time token expires it will refresh a new one using refresh-token.
But it looks like it don't care about whether user is interacting with web app or not. So as long as refresh-token is alive, the browser can always get a new short-life JWT.
So the question is: How to extend token expiring time if user is not active for a set period using JWT?
When the user interacts with your server then your server can decide to issue another JWT with a new expiration time (not at each request but e.g. 5 min before the current JWT expiration time). If the client receives a new JWT, then it replaces the old one.
When the user does nothing, no new JWT is issued and the JWT will become invalid after the timeout.
If the user is active, then issue a new JWT every time the user enter in the web application and every period of time (for example 1 hour)
If the user is not active but the browser is open, it can request a new JWT to server in background. The token must be requested before expiry time and then replace the token in localStorage or cookie. This technique also can be applied to standalone applications
If browser can not request a new token (closed, not active, etc) then the token will expire and you can redirect user to login in the some way that if server session expires
Check this JWT (JSON Web Token) automatic prolongation of expiration

Is the IdentityServer3 session configurable so it expires when the access token expires?

I need the IdentityServer3 session to expire at the same time as the access token. When the access token expires the user is being redirected to IdSvr it's just automatically issuing new Id and Access tokens. I want to force the user to authenticate again when the access token expires. I'm using the Implicit flow so I don't believe refresh token lifetimes come into play. I'm also using the OIDC-client-JS library.
Your approach doesn't make sense -- what would happen if there were 2 different access tokens?
The better approach is from the client to pass the prompt=login or max_age parameter on the authorization request. See the docs for more info: https://identityserver.github.io/Documentation/docsv2/endpoints/authorization.html