c# - 在 C# 中延长 JWT 时间
问题描述
我有这个过滤器(如下),我想延长令牌的时间(通过替换令牌并为用户重新编写一个新的)......有人可以帮我实现这个吗?
这是标准过滤器,没有任何自定义更改或任何东西,我已经处理了令牌到期,现在我想在令牌到期时间内发出请求时更新令牌
public class JwtAuthenticationAttribute : Attribute, IAuthenticationFilter
{
public string Realm { get; set; }
public bool AllowMultiple => false;
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
var request = context.Request;
var authorization = request.Headers.Authorization;
if (authorization == null || authorization.Scheme != "Bearer")
return;
if (string.IsNullOrEmpty(authorization.Parameter))
{
context.ErrorResult = new AuthenticationFailureResult("Missing Jwt Token", request);
return;
}
var token = authorization.Parameter;
var principal = await AuthenticateJwtToken(token);
if (principal == null)
context.ErrorResult = new AuthenticationFailureResult("Invalid token", request);
else
context.Principal = principal;
// HERE SHOULD BE THE IMPLEMENTATION FOR TOKEN RENEWAL
}
private static bool ValidateToken(string token, out string username)
{
username = null;
var simplePrinciple = JwtManager.GetPrincipal(token);
var identity = simplePrinciple?.Identity as ClaimsIdentity;
if (identity == null)
return false;
if (!identity.IsAuthenticated)
return false;
var usernameClaim = identity.FindFirst(ClaimTypes.Name);
username = usernameClaim?.Value;
if (string.IsNullOrEmpty(username))
return false;
// More validate to check whether username exists in system
return true;
}
protected Task<IPrincipal> AuthenticateJwtToken(string token)
{
string username;
if (ValidateToken(token, out username))
{
// based on username to get more information from database in order to build local identity
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username)
// Add more claims if needed: Roles, ...
};
var identity = new ClaimsIdentity(claims, "Jwt");
IPrincipal user = new ClaimsPrincipal(identity);
return Task.FromResult(user);
}
return Task.FromResult<IPrincipal>(null);
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
Challenge(context);
return Task.FromResult(0);
}
private void Challenge(HttpAuthenticationChallengeContext context)
{
string parameter = null;
if (!string.IsNullOrEmpty(Realm))
parameter = "realm=\"" + Realm + "\"";
context.ChallengeWith("Bearer", parameter);
}
}
解决方案
推荐阅读
- algorithm - 总和为值 b 的浮点数数组。给定一个整数 c,我如何确保 sum(每个数组元素 / c) == b / c
- java - 如何更改 JEditorPane 中选定文本的颜色?
- scala - 奇怪的 scala 元组行为
- python - 我该如何解决?该应用程序在 API 密钥中显示错误,就像 (KeyError: 'Api Key not found.')
- swift - SwiftUI 中@State 变量的生命周期是什么?
- git - 每次更改相同的文件时是否会发生合并冲突?
- javascript - 从数组中计算单词分数
- linux - 如何让我的 VPS 开始使用通过 HostMonster 购买的额外磁盘空间?
- swift - macOS 本地和远程通知停止工作——不再有设备令牌
- python - 站在数组中的附近元素 - python