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

前端 未结 2 1146
傲寒
傲寒 2020-12-17 20:18

I have this JWT authorization configuration in my Startup.cs:

services.AddAuthentication(opts =>
{
    opts.DefaultAuthenticateScheme = JwtBearerDefaults.         


        
2条回答
  •  無奈伤痛
    2020-12-17 20:57

    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.

提交回复
热议问题