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

前端 未结 2 1143
傲寒
傲寒 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.

    0 讨论(0)
  • 2020-12-17 21:05

    Thanks for your suggestion... after spending a good time on google i could find your post and that worked for me. You raised a very good point because it does not make sense for app API calls.

    However, I have a situation where the Actions called from the app has a specific notation route (/api/[Controller]/[Action]) which makes me possible to distinguish if my controller has been called by Browser or App.

    app.UseStatusCodePages(async context =>
    {            
        var request = context.HttpContext.Request;
        var response = context.HttpContext.Response;
        var path = request.Path.Value ?? "";
    
        if (response.StatusCode == (int)HttpStatusCode.Unauthorized && path.StartsWith("/api", StringComparison.InvariantCultureIgnoreCase))
        {
            response.Redirect("~/Account/Login");
        }
    });
    
    0 讨论(0)
提交回复
热议问题