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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Building Resilient Identity Systems: Lessons from Securing Billions of Authentication Requests
  • Secure by Design: Modernizing Authentication With Centralized Access and Adaptive Signals
  • MuleSoft OAuth 2.0 Provider: Password Grant Type
  • The Evolution of User Authentication With Generative AI

Trending

  • AI-Driven Test Automation Techniques for Multimodal Systems
  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  • Building an AI/ML Data Lake With Apache Iceberg
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  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.6K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building Resilient Identity Systems: Lessons from Securing Billions of Authentication Requests
  • Secure by Design: Modernizing Authentication With Centralized Access and Adaptive Signals
  • MuleSoft OAuth 2.0 Provider: Password Grant Type
  • The Evolution of User Authentication With Generative AI

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!