DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Your API Authentication Isn’t Broken; It’s Quietly Failing in These 6 Ways
  • Context-Aware Authorization for AI Agents
  • Leveraging AI-Based Authentication Factors in Modern Identity and Access Management Solutions
  • A Framework for Securing Open-Source Observability at the Edge

Trending

  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • LLM Agents and Getting Started with Them
  • Alternative Structured Concurrency
  • The Missing `bandit` for AI Agents: How I Built a Static Analyzer for Prompt Injection
  1. DZone
  2. Coding
  3. Languages
  4. Global Authorization Filter: .NET Core Security, Part V

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.

By 
Neel Bhatt user avatar
Neel Bhatt
·
Updated Apr. 10, 18 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
29.9K Views

Join the DZone community and get the full member experience.

Join For Free

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!

authentication .NET Filter (software) security

Published at DZone with permission of Neel Bhatt. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Your API Authentication Isn’t Broken; It’s Quietly Failing in These 6 Ways
  • Context-Aware Authorization for AI Agents
  • Leveraging AI-Based Authentication Factors in Modern Identity and Access Management Solutions
  • A Framework for Securing Open-Source Observability at the Edge

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook