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

前端 未结 2 1151
傲寒
傲寒 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 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");
        }
    });
    

提交回复
热议问题