授权策略失败时重定向到自定义错误页面

时间:2019-05-14 20:12:28

标签: asp.net-core

我创建了一个授权策略,并将处理程序注册在startup.cs文件中。当策略失败时,我想将用户重定向到自定义错误页面,但始终将其重定向到/ Account / AccessDenied?ReturnUrl = MyPage。我似乎无法弄清楚如何注册自定义错误页面。我尝试了一些选项,例如使用app.UseStatusCodePages。任何帮助是极大的赞赏 启动。 Cs

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddAuthorization(options =>
               {

                   options.AddPolicy("HomePolicyTestPolicy", policy => policy.Requirements.Add(new AuthorizedPermissionsRequirement(new List<UserPermissionsEnum>() { UserPermissionsEnum.ADEAdmin })));
               });
                services.AddSingleton<IAuthorizationHandler, AuthorizedPermissionsHandler>();

            }

            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env, IHttpContextAccessor accessor)
            {
                if (env.IsLocalOrDevelopment())
                {
                    app.UseExceptionHandler("/Home/Error");
                    // app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    app.UseHsts();
                }

                app.UseStaticFiles();
                app.UseAuthentication();
                app.UseSession();

                app.UseStatusCodePages(async context =>
                {
                    if (context.HttpContext.Response.StatusCode == 403)
                    {
                        context.HttpContext.Response.Redirect("/Error/Index");
                    }
                });


            }
Handler:

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AuthorizedPermissionsRequirement requirement)
            {
                context.Fail();

                return Task.CompletedTask;
            }
Controller:

     [Authorize(Policy = "HomePolicyTestPolicy")]
            public IActionResult PolicyTest()
            {
                return View();
            }

结果:它总是将我重定向到/ Account / AccessDenied?ReturnUrl = PolicyTest。我不知道让它重定向到Home / Error。

2 个答案:

答案 0 :(得分:0)

您可以使用状态码页面中间件,签出handle errors

app.UseStatusCodePages(async context => {
  if (context.HttpContext.Response.StatusCode == 403)
  {
     // redirect to page
  }
});

答案 1 :(得分:0)

实现此目标的最佳方法是不要使用context.Fail(),而是这样做:

替换:

context.Fail();

具有:

var mvcContext = context.Resource as AuthorizationFilterContext;
mvcContext.Result = new RedirectToActionResult("MyAction", "MyController", null);
context.Succeed(requirement);

允许上下文成功执行,将执行上下文,该上下文现在是重定向。