DanielFawcett
DanielFawcett

Reputation: 151

Blazor Authentication - Refresh Token for JWT token

I’ve based my authentication on this git hub repository.

https://github.com/chrissainty/AuthenticationWithClientSideBlazor

I’m just wondering if any one has any suggestions on how to implement a refresh token as currently everything I’ve tried has failed.

When does blazor recheck authentication because all I gather is it checks on load, so when my token expires whilst still logged in I get unauthorised http errors. I don’t want to log the user out to re-authenticate.

This is for a blazor web assembly app.

Any advise would be massively appreciated!

Upvotes: 1

Views: 2701

Answers (1)

Tethys
Tethys

Reputation: 21

The general idea is:

Server:

  1. Generate refresh token during login You can choose whatever method you want. For simplicity just generate random set of characters, for example:
private string GenerateRefreshToken()
{
    Random random = new Random();
    byte[] baseBytes = new byte[128];
    random.NextBytes(baseBytes);
    return Convert.ToBase64String(baseBytes);
}
  1. Store it with expiration date (like 2 weeks) and refrence to user
  2. Expand LoginController.Login to return both tokens instead of one
  3. Add new endpoint to LoginController (or extend existing one) - LoginUsingRefreshToken

Here you login again your user using refresh token. Because you stored refresh token you know exactly which user want to login again. Extend (or not, choose your approach) expiration date of this particular refresh token.


Client:

  1. Store refresh token like you stored "regular" token
 await _localStorage.SetItemAsync("refreshToken", loginResult.RefreshToken);
  1. Check if regular token expired. You can do it in many ways:

    Deserialize token before every request and check expiration date Act dynamicly: when you receive 401 from Server Set timer to relogin before token expires Or pick something else

  2. Do a relogin using refresh token and newly created endpoint

Upvotes: 2

Related Questions