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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Containers Trend Report: Explore the current state of containers, containerization strategies, and modernizing architecture.

Low-Code Development: Learn the concepts of low code, features + use cases for professional devs, and the low-code implementation process.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • Securing REST APIs With Nest.js: A Step-by-Step Guide
  • Harnessing the Power of APIs: Shaping Product Roadmaps and Elevating User Experiences through Authentication
  • Navigating the API Seas: A Product Manager's Guide to Authentication
  • What Are the Pillars of API Security?

Trending

  • IoT Cloud Computing in IoT: Benefits and Challenges Explained
  • Navigating Software Leadership in a Dynamic Era
  • My Top Picks of Re: Invent 2023
  • The Role of Metadata in Data Management
  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.

Neel Bhatt user avatar by
Neel Bhatt
·
Updated Apr. 10, 18 · Tutorial
Like (2)
Save
Tweet
Share
29.0K 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

  • Securing REST APIs With Nest.js: A Step-by-Step Guide
  • Harnessing the Power of APIs: Shaping Product Roadmaps and Elevating User Experiences through Authentication
  • Navigating the API Seas: A Product Manager's Guide to Authentication
  • What Are the Pillars of API Security?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • 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: