【问题标题】:How to display an not authorize page on ASP.NET Core如何在 ASP.NET Core 上显示未授权页面
【发布时间】:2017-03-14 09:04:48
【问题描述】:

使用[Authorize] 属性时如何在 ASP.NET Core 上显示错误页面?

政策

services.AddAuthorization(p =>
{
    p.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
    p.AddPolicy("RequireTrainerRole", policy => policy.RequireRole("Trainer"));
    p.AddPolicy("RequireTeamLeaderRole", policy => policy.RequireRole("Team Leader"));
    p.AddPolicy("RequireUserRole", policy => policy.RequireRole("User"));
});

控制器

[Authorize(Policy = "RequireAdminRole")]
[Area("Admin")]
public class BaseController : Controller
{
}

【问题讨论】:

    标签: asp.net-core asp.net-identity


    【解决方案1】:

    如果您使用 cookie 身份验证来保护您的资源,那么您可以使用 AccessDeniedPath 属性重定向到错误页面:

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AccessDeniedPath = "<path>"
            });
    

    否则你可以使用UseStatusCodePages处理403

    app.UseStatusCodePages(new StatusCodePagesOptions()
     {
         HandleAsync = (ctx) =>
         {
              if (ctx.HttpContext.Response.StatusCode == 403)
              {
                   //handle
              }
    
              return Task.FromResult(0);
         }
     }); 
    

    【讨论】:

      猜你喜欢
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      相关资源
      最近更新 更多