![](/img/trans.png)
[英]How to implement JWT Refresh Tokens in asp.net core web api (no 3rd party)?
[英]asp.net core jwt refresh tokens without saving anywhere
我已经在 asp.net 框架中实现了刷新令牌,如下所示。 它不需要将刷新令牌保存在任何地方。 我可以在 asp.net core jwt 令牌中做同样的事情吗? 我想要的不是将刷新令牌保存在数据库或其他任何地方
public class RefreshTokenProvider : IAuthenticationTokenProvider
{
public async Task CreateAsync(AuthenticationTokenCreateContext context)
{
Create(context);
}
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
Receive(context);
}
public void Create(AuthenticationTokenCreateContext context)
{
object inputs;
context.OwinContext.Environment.TryGetValue("Microsoft.Owin.Form#collection", out inputs);
var grantType = ((FormCollection)inputs)?.GetValues("grant_type");
var grant = grantType.FirstOrDefault();
if (grant == null || grant.Equals("refresh_token")) return;
context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);
context.SetToken(context.SerializeTicket());
}
public void Receive(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
if (context.Ticket == null)
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
context.Response.ReasonPhrase = "invalid token";
return;
}
if (context.Ticket.Properties.ExpiresUtc <= DateTime.UtcNow)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
context.Response.ReasonPhrase = "unauthorized";
return;
}
context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);
context.SetTicket(context.Ticket);
}
}
JWT 令牌在使用 JWT 中间件时会自动刷新并保存在内存中。 根据我的理解,您不需要编写任何类型的代码。 只需将 jwt 设置为服务。 如果从客户端发送 JWT 令牌,它将在服务器端刷新。
JWT 令牌信息存储在内存中,而不是任何类型的数据库中。 毕竟,您必须知道要接受什么令牌以及要拒绝什么令牌,因为不可能不在任何地方存储任何东西。 您不需要单独的令牌。 只需 JWT 为您处理刷新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.