问题
I've successfully setup authentication in my AspNetCore API application using JWT + HttpOnly Cookies, inspired by this document and this topic.
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;
}
};
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.
How can I solve this?
UPDATE 1
This is what I actually do:
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);
};
Here is where I want to add Token-Expired header, but based on what?
回答1:
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();
});
来源:https://stackoverflow.com/questions/58102289/how-to-properly-refresh-a-token-using-jwt-httponly-cookie