Holt
Holt

Reputation: 452

JWT Expire Behavior

I am new to the world of JWT (and honestly security in general). I have a .NET Core2 service that is secured using a JWT bearer token. From the client perspective, what should happen once the token expires and sends a 401Unauthorized response? Do I expect the client to request a new token by themselves?

If it is expected that the client requests a new token...does this mean that on each API call that is made to my service has to be wrapped with code that checks for 401Unauthorized, knows to call to a different endpoint to create a new valid token, and then remake the original call with the new token?

I am unsure how to make a nice user experience if a particular webpage is being loaded right when a token is expiring (part of the page is loaded using tokenA and then the rest of the page needs to be loaded using tokenB).

Upvotes: 1

Views: 699

Answers (2)

djbyter
djbyter

Reputation: 793

Check out the usage and implementation of refresh tokens. The idea here is that the initial request for token generates a refresh token as well as the normal token. The normal tokens are shorter lived, while the refreshes are longer. Yes, when you make a call you need to check to see if a) the token is already expired and b) what their response is and coordinate to get an updated token automatically. It should be transparent to the user.

Some more details here: https://www.blinkingcaret.com/2018/05/30/refresh-tokens-in-asp-net-core-web-api/

Upvotes: 1

Daniel
Daniel

Reputation: 11192

It is very normal for a client with a backend that utilizes JWT to have the functionality you describe.

Usually the backend will return a 401 (often accompanied with a {"message": "Access token expired"} body).

So the class that handles requests to the backend usually has the request function wrapped in a try catch.

If the request fails you can check for 401 errorcode and the "Access token expired" message, and then refresh the token and re-run the request.

Also you can also (prior to the request) decode the JWT token and check if it expired (by looking at the expiration time). Then you can perform the refresh token call before you make the intended request.

Both methods will cause a slight delay in loading the site, but likely (depending on your API performance) it will be a very minor delay.

Remember to make sure you can somehow differentiate between a regular 401 Unauthorized and a access-token-expired error from the backend.

Upvotes: 2

Related Questions