Global Authorization Filter in ASP.NET Core
This blog is going to explain how to authorize the ASP.NET Core application globally. That is, it is not necessary to add the [Authorize] attribute to each controller or action method. The global authorization filter helps you to authorize the entire application. You can achieve this in a few steps.
Step 1:
Add the following code to the Startup.cs file in ConfigureServices mode. In the code first, the authorization policy has been created using AuthorizationPolicyBuilder(). It has several methods to create authorization policies. Here I have added the RequireAuthenticatedUser() method. It checks whether the user is authenticated or not. Similar to the [Authorize] filter. By adding this method you do not have to add the [Authorize] filter attribute to all controllers and methods. Finally, the global authorization filter is added using config.Filters.Add(new AuthorizeFilter(policy));
public void ConfigureServices(IServiceCollection services) { ... ... ... var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); services.AddMvc(config => { config.Filters.Add(new AuthorizeFilter(policy)); }); services.AddControllersWithViews(); }
Step 2:
You must add the [AllowAnonymous] attribute to the controller or action method that does not require authentication. For example, login page, register page, etc. If you want that the entire controller does not require authentication, add the [AllowAnonymous] attribute to the controller level. The following code snippets explaining how to add the controller level [AllowAnonymous] attribute.
(I did not include action method coding for simplicity of code. You can check the simple cookie authentication blog if you wish).
[AllowAnonymous] public class AccountController : Controller { [HttpGet] public ActionResult Login() { // Login code } [HttpPost] public async Task<ActionResult> Login(Users user) { // Login code } [HttpPost] public async Task<ActionResult> Logout() { // logout code } }
If you want to make anonymous a particular action method, that means you do not have to log in to access that page. You can add the [AllowAnonymous] attribute to that action method. By doing so, all action methods in the controller verify the authentication, but the [AllowAnonymous] added method does not verify the authentication.
Method levelpublic class AccountController : Controller { [AllowAnonymous] [HttpGet] public ActionResult Login() { // Login code } }
Note:
If you do not add the [AllowAnonymous] attribute to the login page it will throw the following error.
HTTP Error 404.15 - Not Found
The request filtering module is configured to deny a request where the query string is too long.
I hope this helps you. Keep coding.
Similar Article
Simple Cookie Authentication in ASP.NET Core
Comments
Post a Comment