How to return 401 instead of 302 in ASP.NET Core?

后端 未结 8 2082
迷失自我
迷失自我 2020-11-29 03:36

I\'m trying to get ASP.NET Core Identity to return 401 when a user isn\'t logged in. I\'ve added an [Authorize] attribute to my method and instead of returning

相关标签:
8条回答
  • 2020-11-29 04:11

    If the request header contains X-Requested-With: XMLHttpRequest the status code will be 401 instead of 302

    private static bool IsAjaxRequest(HttpRequest request)
        {
            return string.Equals(request.Query["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) ||
                string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal);
        }
    

    See on gitHub: https://github.com/aspnet/Security/blob/5de25bb11cfb2bf60d05ea2be36e80d86b38d18b/src/Microsoft.AspNetCore.Authentication.Cookies/Events/CookieAuthenticationEvents.cs#L40-L52

    0 讨论(0)
  • 2020-11-29 04:15

    In continuation, I merged the previous answers into the following:

    1. Startup.cs

    services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = new PathString("/Account/Login");
                options.LogoutPath = new PathString("/Account/Logout");
    
                options.Events.OnRedirectToAccessDenied = context =>
                {
                    if (wlt_AjaxHelpers.IsAjaxRequest(context.Request))
                    {
                        context.Response.Clear();
                        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        return Task.CompletedTask;
                    }
                    context.Response.Redirect(context.RedirectUri);
                    return Task.CompletedTask;
                };
            });
    

    2. Helper custom class

    public static class wlt_AjaxHelpers
         {
    
            public static bool IsAjaxRequest( HttpRequest request )
            {
    
                return string.Equals(request.Query["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) ||
                    string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal);
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题