Search code examples
asp.net-core-mvc.net-6.0asp.net-authorization

How to add global authorize attribute to ASP.NET Core 6 MVC?


I want to set [Authorize] data attribute to the application rather then controllers

[Authorize]
public class CustomerController : Controller {}

With this [Authorize] I can set authorization only for this controller; I want to set it for every controller.

So far I tried these in the program.cs class...

var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();

services.AddMvc(config =>
{
    config.Filters.Add(new AuthorizeFilter(policy));
});

Both didn't work - it builds the app but on browser it doesn't reach to website. So how can I set this attribute globally in .NET 6 ?

builder.services.AddMvc(options => options.Filters.add(new AuthorizeAttribute));

This throws an error

Cannot resolve method 'Add(Microsoft.AspNetCore.Authorization.AuthorizeAttribute)'


Solution

  • The way to do this in ASP.NET Core 6.0 is a little different. Microsoft Docs has an article that shows two ways to do this: Create an ASP.NET Core app with user data protected by authorization - Require authenticated users.

    Option 1 - what the article calls "the preferred way" - add the following code to your Program.cs file:

    builder.Services.AddAuthorization(options =>
    {
        options.FallbackPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
    });
    

    Option 2 - the article shows an alternative way using an authorization filter:

    builder.Services.AddControllers(config =>
    {
        var policy = new AuthorizationPolicyBuilder()
                         .RequireAuthenticatedUser()
                         .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    });