How to redirect to log in page on 401 using JWT authorization in ASP.NET Core

You may use StatusCodePages middleware. Add the following inot your Configure method:

app.UseStatusCodePages(async context => {
    var request = context.HttpContext.Request;
    var response = context.HttpContext.Response;

    if (response.StatusCode == (int)HttpStatusCode.Unauthorized)   
       // you may also check requests path to do this only for specific methods       
       // && request.Path.Value.StartsWith("/specificPath")

       {
           response.Redirect("/account/login")
       }
    });

I read that this shouldn’t automatically redirect because it won’t make sense to API calls

this relates to API calls, that returns data other than pages. Let’s say your app do call to API in the background. Redirect action to login page doesn’t help, as app doesn’t know how to authenticate itself in background without user involving.

Leave a Comment