1

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?

ssnake
  • 229
  • 5
  • 15
  • Right.. So essentially you need to somehow not redirect to login, but just return a 401 result with that header? – juunas Sep 25 '19 at 17:35
  • I have to return 401 without any particular header when no access token is provided or if it is invalid (I already do this), and 401 with Token-Expired header if access token is expired, to tell the client to do a request for refresh tokens. – ssnake Sep 25 '19 at 18:59

1 Answers1

2

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();
        });
DanielSan
  • 56
  • 2