问题描述
I've successfully setup authentication in my AspNetCore API application using JWT + HttpOnly Cookies, inspired by this document and this topic.
现在,我正在尝试集成刷新令牌功能.我发现此教程,但它仅基于JWT身份验证,因此我陷入了在响应中添加 Token-Expired 标头的问题:
Now I'm trying to integrate refresh token feature.I've found this tutorial, but it is based on JWT only authentication and I'm stuck at the point where I should add a Token-Expired header to the response:
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
因为我使用的是基于Cookie的身份验证,所以我使用 OnRedirectToLogin 事件而不是 OnAuthenticationFailed 事件,以及我无法使用 context.Exception.GetType() 方法.因此,我不知道该如何确定是否需要刷新令牌.
Because I'm using cookie based authentication, I use OnRedirectToLogin event instead of OnAuthenticationFailed event, and the context.Exception.GetType() method is not available to me.So I don't know how to figure out that a refresh token is needed.
我该如何解决?
更新1
这实际上是我要做的:
options.Events.OnRedirectToLogin = context =>
{
if (context.Request.Path.StartsWithSegments("/api"))
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
else
context.Response.Redirect(context.RedirectUri);
return Task.FromResult(0);
};
在这里我要添加 Token-Expired 标头,但是基于什么?
Here is where I want to add Token-Expired header, but based on what?
推荐答案
使用将您的cookie添加到承载标头的中间件,如下所示:
Use a middleware that add your cookie to bearer header like this:
app.Use(async (context, next) =>
{
var token = context.Request.Cookies["access_token"];
if (!string.IsNullOrEmpty(token)) context.Request.Headers.Add("Authorization", "Bearer " + token);
await next();
});
这篇关于如何使用JWT + HttpOnly Cookie正确刷新令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!