ASP.net-core 3.0 - 当用户不在策略中时,是否可以 return 自定义错误页面?

ASP.net-core 3.0 - Is it possible to return custom error page when user is not in a policy?

我正在创建一个 Intranet 网站,但在身份验证部分遇到了一些问题。我想将控制器的访问权限限制为具有特定 Active Directory 角色的用户。如果用户不在指定的角色中,则应将他重定向到自定义错误页面。

Windows 身份验证已启用。我尝试了以下解决方案:

我在 Startup.cs 的 ConfigureServices 方法中创建了自定义策略:

 ...
 services.AddAuthorization(options =>
        {
            options.AddPolicy("ADRoleOnly", policy =>
            {
                policy.RequireAuthenticatedUser();
policy.RequireRole(Configuration["SecuritySettings:ADGroup"], Configuration["SecuritySettings:AdminGroup"]);
            });
        });
services.AddAuthentication(IISDefaults.AuthenticationScheme);

 ....

在我的 appsettings.json 我的活动目录组中(当然不是我真正使用的那个):

   "SecuritySettings": {
      "ADGroup": "MyDomain\MyADGroup",
      "AdminGroup": "MyDomain\MyAdminGroup"
 }}

在我的 Configure 方法中:

...
 app.UseAuthorization();
 app.UseAuthentication();
 app.UseStatusCodePagesWithReExecute("/Home/ErrorCode/{0}");
...

我有以下控制器:

 [Area("CRUD")]
 [Authorize(Policy = "ADRoleOnly")]
 public class MyController : Controller

我有一个具有以下方法的 HomeController:

    [AllowAnonymous]
    public IActionResult ErrorCode(string id)
    {
        return View();
    }

但是当我调试我的网站时,这个方法从来没有达到过。

如果我是策略指定角色之一的用户,它会按预期工作。

但如果我不是角色的成员,我将被重定向到默认导航器页面。

我想重定向到自定义错误页面。我认为那是

的目的
   app.UseStatusCodePagesWithReExecute("/Home/ErrorCode/{0}");

策略失败时会生成403状态码,app.UseStatusCodePagesWithReExecute不检测403:

您可以编写自定义中间件来处理它:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

        if (env.IsDevelopment())
        {

            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.Use(async (context, next) =>
        {
            await next();

            if (context.Response.StatusCode == 403)
            {

                var newPath = new PathString("/Home/ErrorCode/403");
                var originalPath = context.Request.Path;
                var originalQueryString = context.Request.QueryString;
                context.Features.Set<IStatusCodeReExecuteFeature>(new StatusCodeReExecuteFeature()
                {
                    OriginalPathBase = context.Request.PathBase.Value,
                    OriginalPath = originalPath.Value,
                    OriginalQueryString = originalQueryString.HasValue ? originalQueryString.Value : null,
                });

                // An endpoint may have already been set. Since we're going to re-invoke the middleware pipeline we need to reset
                // the endpoint and route values to ensure things are re-calculated.
                context.SetEndpoint(endpoint: null);
                var routeValuesFeature = context.Features.Get<IRouteValuesFeature>();
                routeValuesFeature?.RouteValues?.Clear();

                context.Request.Path = newPath;
                try
                {
                    await next();
                }
                finally
                {
                    context.Request.QueryString = originalQueryString;
                    context.Request.Path = originalPath;
                    context.Features.Set<IStatusCodeReExecuteFeature>(null);
                }

                // which policy failed? need to inform consumer which requirement was not met
                //await next();
             }

        });
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();



        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }