Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an not authorize page on ASP.NET Core

How can i display an error page on ASP.NET Core when using [Authorize] attribute?

Policy

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"));
});

Controller

[Authorize(Policy = "RequireAdminRole")]
[Area("Admin")]
public class BaseController : Controller
{
}
like image 955
Cristian Szpisjak Avatar asked Nov 01 '16 08:11

Cristian Szpisjak


1 Answers

If you use cookie authentication to protect your resources then you could use AccessDeniedPath property to redirect to error page:

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

Otherwise you can handle 403 with using UseStatusCodePages

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

          return Task.FromResult(0);
     }
 }); 
like image 107
adem caglin Avatar answered Oct 12 '22 23:10

adem caglin