How to properly refresh a token using JWT + HttpOnly Cookie?

懵懂的女人 提交于 2021-01-29 17:50:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!