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

后端 未结 8 2080
迷失自我
迷失自我 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 03:52

    For me on ASP.NET Core 2.2.0 only this worked:

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(
            options =>
            {
                options.LoginPath = new PathString("/Account/Login");
                options.LogoutPath = new PathString("/Account/Logout");
    
                options.Events.OnRedirectToLogin = context =>
                {
                    if (context.Request.Path.StartsWithSegments("/api")
                        && context.Response.StatusCode == StatusCodes.Status200OK)
                    {
                        context.Response.Clear();
                        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        return Task.CompletedTask;
                    }
                    context.Response.Redirect(context.RedirectUri);
                    return Task.CompletedTask;
                };
            }
        );
    

提交回复
热议问题