当 AuthorizeFilter 失败时如何返回 403 而不是重定向到拒绝访问

Lie*_*ero 12 c# asp.net-core-mvc asp.net-core asp.net-core-2.2

在 Startup.ConfigureServices() 我配置授权过滤器是这样的:

services.AddMvc(options =>
{
    options.Filters.Add(new AuthorizeFilter(myAuthorizationPolicy));
})
Run Code Online (Sandbox Code Playgroud)

我使用基于配置的 cookie 身份验证或 AAD 身份验证:

if (useCookieAuth)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie();
}
else
{
    services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
       .AddAzureAD(options => Configuration.Bind("Authentication:AzureAd", options));
}
Run Code Online (Sandbox Code Playgroud)

现在,当我访问一个页面并myAuthorizationPolicy失败时,我被重定向到“Account/AccessDenied?ReturnUrl=%2F”,但我想返回 403。

Bor*_*lov 20

看来您必须覆盖 OnRedirectToAccessDenied

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options => {
        options.Events.OnRedirectToAccessDenied = context => {
             context.Response.StatusCode = 403;
             return Task.CompletedTask;
        };
    });
Run Code Online (Sandbox Code Playgroud)


Joh*_*lly 5

对于那些使用 Azure AD 并在他们的应用中使用的人(咳咳ConfigureServices

services.AddMicrosoftIdentityWebAppAuthentication(Configuration);
Run Code Online (Sandbox Code Playgroud)

解决方案是添加以下内容:

        services.Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme, options =>
        {
            options.Events.OnRedirectToAccessDenied = new Func<RedirectContext<CookieAuthenticationOptions>, Task>(context =>
            {
                context.Response.StatusCode = StatusCodes.Status403Forbidden;
                return context.Response.CompleteAsync();
            });
        });
Run Code Online (Sandbox Code Playgroud)

这样,ASP.NET 将不再重定向到AccessDenied,而是返回 a 403

更多详细信息可以在这里找到: https: //blog.johnnyreilly.com/2020/12/21/how-to-make-azure-ad-403/(但我希望您真正需要的就是这个答案)


小智 0

public class AuthorizeOrForbidAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new HttpStatusCodeResult(403);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

尝试上面的过滤器。