如何修改 ASP.NET 核心中的默认授权属性?

How to modify default Authorize attribute in ASP.NET Core?

我需要修改默认的授权属性,以便它重定向到“未找到”视图而不是默认的“拒绝访问”视图,我该怎么做?

您可以使用此配置更改 AccessDeniedPathLogoutPathLoginPath 路径 ConfigureServices 启动方法 class

public void ConfigureServices(IServiceCollection services)
{
    //
    services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = "/AccessDenied";//<--NOTE THIS
                options.LogoutPath = "/Acconut/LogOut";
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromDays(15);
                options.LoginPath = "/Account/Login";
                options.ReturnUrlParameter = "returnUrl";
                options.SlidingExpiration = false;
                options.Cookie.IsEssential = true;
                options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
            });
    //
}

您可以创建一个策略(例如 [Authorize(Policy = "NotFoundPagePlolicy")])并在应用程序的 Startup.cs 中注册该策略以执行一些代码块。

在 Startup/ConfigureServices() 中:

services.AddAuthorization(options =>
{
    options.AddPolicy("NotFoundPagePlolicy", 
        policy => policy.Requirements.Add(new Authorization.NotFoundPagePloliyRequirement()));
}); 

在控制器中:

[Authorize(Policy = "NotFoundPagePlolicy")]

在NotFoundPagePloliyRequirement.cs中:

public class NotFoundPagePloliyRequirement: AuthorizationHandler<NotFoundPagePloliyRequirement>, IAuthorizationRequirement
{
        public override void Handle(AuthorizationHandlerContext context, NotFoundPagePloliyRequirement requirement)
        {
// Your custom code code 
        }
    }

更多详情,请参考:https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-3.1

您似乎想覆盖 onRedirecttoAccessDenied 事件。您可以在 Startup class.

ConfigureServices 方法中执行此操作
        services.ConfigureApplicationCookie(options =>
        {
            options.Events.OnRedirectToAccessDenied = context =>
            {                    
                context.Response.StatusCode = StatusCodes.Status404NotFound;                    
                return Task.CompletedTask;
            };
        });