简体   繁体   English

Blazor 身份验证 - JWT 令牌的刷新令牌

[英]Blazor Authentication - Refresh Token for JWT token

I've based my authentication on this git hub repository.我的身份验证基于此 git hub 存储库。

https://github.com/chrissainty/AuthenticationWithClientSideBlazor https://github.com/chrissinty/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. blazor 什么时候重新检查身份验证,因为我收集的是它在加载时检查,所以当我的令牌过期但仍然登录时,我会收到未经授权的 http 错误。 I don't want to log the user out to re-authenticate.我不想注销用户重新进行身份验证。

This is for a blazor web assembly app.这是一个 blazor web 程序集应用程序。

Any advise would be massively appreciated!任何建议将不胜感激!

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 周)一起存储并供用户参考
  2. Expand LoginController.Login to return both tokens instead of one展开 LoginController.Login 以返回两个令牌而不是一个
  3. Add new endpoint to LoginController (or extend existing one) - LoginUsingRefreshToken向 LoginController 添加新端点(或扩展现有端点) - 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在每个请求之前反序列化令牌并检查到期日期动态操作:当您从服务器收到 401 时设置计时器以在令牌到期前重新登录或选择其他内容

  2. Do a relogin using refresh token and newly created endpoint使用刷新令牌和新创建的端点重新登录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM