Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Global Authorization Filter: .NET Core Security, Part V

DZone's Guide to

Global Authorization Filter: .NET Core Security, Part V

We continue our series on .NET Core security by examining how developers can globally add authentication processes to their web applications.

· Security Zone ·
Free Resource

Discover how to provide active runtime protection for your web applications from known and unknown vulnerabilities including Remote Code Execution Attacks.

You can find all of my .NET C0re 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 function in your .NET Core application.

Let us assume we need to add Authorize filter globally which means we are no longer required to add that one-by-one on all our app's 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 a 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, to implement authorization, we can do the following:

public void ConfigureServices(IServiceCollection services)
{

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

//// Other code

}

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

So, to add authorization 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 access to 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 globally added authorization with this simple policy.

Multiple Policies With Conventions

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

For such a case, we can use conventions.

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

In this custom convention, we will check whether the controller is an 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 a filter with the “policyforapicontrollers” policy if the controller is an API controller.
  • Added a filter with the “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 and told the application to use the JWT Bearer authentication for API controllers.

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

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

Once the convention is created, let us add this convention to the ConfigureService method of the 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 an MVC controller then all the users who are authenticated will be able to access the MVC controllers and actions, and whenever the controller is an API then JWT authentication will be required.

You can modify the above code as per your needs.

Hope this helps!

Find out how Waratek’s award-winning application security platform can improve the security of your new and legacy applications and platforms with no false positives, code changes or slowing your application.

Topics:
.net core ,security ,web application security ,authorization

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}