Global Authorization Filter in .Net Core: .Net Core Security Part – V

1.6

You can find all of my  .Net core posts here.

In these series of posts, we will see how to secure your .Net Core applications.

In this post, we will see how to add the Authorize globally in your .Net Core application.

Let us assume we need to add Authorize filter globally which means we are no more require to add that one by one on all the Controllers and all the actions.

What is Authorization?

  • Authorization determines whether an identity should be granted access to a specific resource
  • Authorization is the process of giving someone permission to do or have something
  • For example, you have a website in which you have different modules, you want to allow the access of some specific modules to some specific set of people – in these types of scenarios you can use Authorization

Simple policy

If you are familiar with MVC then you might know, we can add Authorize globally in MVC by adding the Authorize attribute as below:


GlobalFilters.Filters.Add(new AuthorizeAttribute() { Roles = "Admin, SuperUser" });

In .Net Core, we can add the filters globally by adding it to the MvcOptions.Filters collection in the ConfigureServices method in the Startup class.

So if we talk about Authorize then we can add it as below:


public void ConfigureServices(IServiceCollection services)
{

services.AddMvc(options =>
{
options.Filters.Add(typeof(AuthorizeAttribute));
});

//// Other code

}

But here is a catch. Above code will not work in .Net Core because in .Net Core, the implementation for attribute class and the filters are separated from each other.

So to add Authorize globally in .Net Core, we need to create AuthorizationPolicy and once the policy is created, we can add AuthorizeFilter as below:


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

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

Here you can add roles as well. If you want to allow only SuperAmin roles, then the policy can be written as below:


var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireRole("Admin", "SuperUser")
.Build();

As you can see above, we have added the Authorize globally with simple policy.

Multiple Policies with Conventions

What if you need a separate policy for Controllers and API controllers?

For such case, we can use the Conventions.

Let us create the custom conventions by inheriting from the IControllerModelConvention interface which allows the customize the ControllerModel

In this Custom convention, we will check whether the controller is MVC controller or API controller, and will add the policy accordingly:


public class AuthorizeControllerModelConvention : IControllerModelConvention
{
  public void Apply(ControllerModel controller)
  {
   if (controller.ControllerName.Contains("Api"))
   {
    controller.Filters.Add(new AuthorizeFilter("policyforapicontrollers"));
   }
  else
  {
    controller.Filters.Add(new AuthorizeFilter("policyforcontrollers"));
  }
 }
}

Here we have:

  • Added filter with “policyforapicontrollers” policy if the controller is API controller
  • Added filter with “policyforcontrollers” policy if the controller is MVC controller

You can add the policy by adding the authorization as below:


services.AddAuthorization(o =>
{
  o.AddPolicy("policyforcontrollers", b =>
  {
   b.RequireAuthenticatedUser();
  });
o.AddPolicy("policyforapicontrollers", b =>
  {
    b.RequireAuthenticatedUser();
    b.RequireClaim(ClaimTypes.Role, "Api");
    b.AuthenticationSchemes = new List<string> { JwtBearerDefaults.AuthenticationScheme };
  });
});

Here we have:

  • Added a normal policy for allowing only authenticated users to access the MVC controllers
  • Added claims for API controllers by and told the application to use the JWT Bearer authentication for API controllers

Note: Now if you do not add the Authorization globally then you need to put attribute [Authorize(Policy = “policyforapicontrollers”)] above all API controller and the attribute [Authorize(Policy = “policyforcontrollers”)] above all MVC controller.

But to make it simpler, we can add the Authorize globally as shown below.

Once the convention is created, let us add this convention to the ConfigureService method of Startup.cs class:


public void ConfigureServices(IServiceCollection services)
{

services.AddMvc(options =>
{
options.Conventions.Add(new AuthorizeControllerModelConvention());
});

//// Other code

}

That is it.

Now, whenever the controller is MVC controller then all the users who are authenticated will be able to access the MVC controllers & actions and whenever the controller is API then JWT authentication will be required.

You can modify above code as per your need.

Hope it helps.

 

4 thoughts on “Global Authorization Filter in .Net Core: .Net Core Security Part – V

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s