Search code examples
asp.net-mvcasp.net-coreasp.net-identity

Site-level [Authorize] in ASP.NET Core Web App (Model-View-Controller)


I'm writing small internal web app (decided to try asp.net for the first time). This app has no public pages, so i need to lock down every page.

First, i started to write this code in every single method of every single controller:

if (User.Identity is { IsAuthenticaed: true }) 
{
  // Do task
} else {
  throw new Exception("Unauthorized")
}

But then I discovered [Authorize]. Now i just writing it on top of every controller! But it's still quite manual, Is there a way to lock down entire website?


Solution

  • If I need to do it once, I can. How i can do that? And also, will it redirect to login page, like [Authorize]

    You can create an a filter globally for all controllers, actions, and Razor Pages ,create an AuthorizeFilter:

    try to add below code :

     // Configure the custom policy
        var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .RequireRole("Admin", "SuperUser")
                .Build();
     // Pass a policy in the constructor of the Authorization filter
        builder.Services.AddControllersWithViews(options =>
        {
            options.Filters.Add(new AuthorizeFilter(policy));
        });
    

    Remember, this policy applies globally so you need to ensure your "Login" and "AccessDenied" pages are decorated with [AllowAnonymous], otherwise you'll end up with endless redirects.