.NET 6.0 - Apply Authorize Attribute to All Controllers
This is a super quick post to show how to add the Authorize Attribute ([AuthorizeAttribute]
) to all controllers by default in a .NET 6.0 application.
IMPORTANT: The solution depends on how your project is setup (thanks for the comment Luiz):
- You have a custom authorize attribute that implements the
IAuthorizationFilter
interface. For an example see .NET 6.0 - JWT Authentication Tutorial with Example API. - You're using the built in authorize attribute from the
Microsoft.AspNetCore.Authorization
namespace.
1. Custom Authorize Attribute
The following instructions are for projects with custom authentication.
Configure with the AddControllers()
method in Program.cs
In your Program.cs file where you add services for controllers using the builder.Services.AddControllers()
method, pass a lambda function to the method to add the Authorize Attribute to the Filters
collection.
The custom Authorize Attribute is a type of filter (IAuthorizationFilter
) in .NET, and the Filters
collection contains filters that apply to all actions in all controllers.
Here's the line of code that adds the auth attribute globally:
services.AddControllers(x => x.Filters.Add<AuthorizeAttribute>());
Example .NET Program.cs file with Global (Custom) Authorize Attribute
This is a complete example .NET 6.0 Program.cs file that adds the custom AuthorizeAttribute
to all controllers on line 13
.
using WebApi.Helpers;
using WebApi.Services;
var builder = WebApplication.CreateBuilder(args);
// add services to DI container
{
var services = builder.Services;
services.AddCors();
// add services for controllers and
// add AuthorizeAttribute to all controllers and actions
services.AddControllers(x => x.Filters.Add<AuthorizeAttribute>());
// configure strongly typed settings object
services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
// configure DI for application services
services.AddScoped<IUserService, UserService>();
}
var app = builder.Build();
// configure HTTP request pipeline
{
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
// custom jwt auth middleware
app.UseMiddleware<JwtMiddleware>();
app.MapControllers();
}
app.Run("http://localhost:4000");
2. Built In (Microsoft.AspNetCore.Authentication
) Authorize Attribute
The following instructions are for projects that use built in .NET 6 authentication and authorization.
Configure with the MapControllers()
method in Program.cs
In your Program.cs file where you configure the HTTP request pipeline using the app.MapControllers()
method, simply append a call to the extension method RequireAuthorization()
.
Here's the line of code that adds the auth attribute globally:
app.MapControllers().RequireAuthorization();
Example .NET Program.cs file with Global (Built In) Authorize Attribute
This is a complete example .NET 6.0 Program.cs file that adds the built in AuthorizeAttribute
to all controllers on line 34
.
using Microsoft.AspNetCore.Authentication;
using WebApi.Helpers;
using WebApi.Services;
var builder = WebApplication.CreateBuilder(args);
// add services to DI container
{
var services = builder.Services;
services.AddCors();
services.AddControllers();
// configure basic authentication
services.AddAuthentication("BasicAuthentication")
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
// configure DI for application services
services.AddScoped<IUserService, UserService>();
}
var app = builder.Build();
// configure HTTP request pipeline
{
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers().RequireAuthorization();
}
app.Run("http://localhost:4000");
Override Authorize Attribute with AllowAnonymous
With either solution, you can override the global authorize attribute on specific action methods and/or controllers with the [AllowAnonymous]
attribute.
For example the below users controller overrides the authorize attribute to allow anonymous access to the authenticate
and register
routes. The rest of the routes require authorization by default because of the configuration in the Program.cs file above.
namespace WebApi.Controllers;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using WebApi.Authorization;
using WebApi.Helpers;
using WebApi.Models.Users;
using WebApi.Services;
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
private IUserService _userService;
private IMapper _mapper;
private readonly AppSettings _appSettings;
public UsersController(
IUserService userService,
IMapper mapper,
IOptions<AppSettings> appSettings)
{
_userService = userService;
_mapper = mapper;
_appSettings = appSettings.Value;
}
[AllowAnonymous]
[HttpPost("authenticate")]
public IActionResult Authenticate(AuthenticateRequest model)
{
var response = _userService.Authenticate(model);
return Ok(response);
}
[AllowAnonymous]
[HttpPost("register")]
public IActionResult Register(RegisterRequest model)
{
_userService.Register(model);
return Ok(new { message = "Registration successful" });
}
[HttpGet]
public IActionResult GetAll()
{
var users = _userService.GetAll();
return Ok(users);
}
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
var user = _userService.GetById(id);
return Ok(user);
}
[HttpPut("{id}")]
public IActionResult Update(int id, UpdateRequest model)
{
_userService.Update(id, model);
return Ok(new { message = "User updated successfully" });
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
_userService.Delete(id);
return Ok(new { message = "User deleted successfully" });
}
}
Update History:
- 05 Jan 2023 - Updated with instructions for built in authorize attribute from the Microsoft.AspNetCore.Authorization namespace.
- 28 Nov 2022 - Published instructions for global custom authorize attribute.
Need Some .NET Help?
Search fiverr for freelance .NET developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!