Loading

ASP.NET Web API

How to Authentication and Authorization in ASP.NET Web API?. The Complete ASP.NET Web API Developer Course 2023 [Videos].

In this Video, I am going to discuss Authentication and Authorization in Web API. Here I will give you an overview of Authentication and Authorization in Web API and from the next Video onwards, we will discuss the practical implementation of Authentication and Authorization in ASP.NET Web API with examples.

Once you create a Web API Service, then the most important thing that you need to take care of is security means you need to control access to your Web API Services. So lets start the discussion with the definition of Authentication and Authorization

Authentication is the process of identifying the user. For example, one user lets say James logs in with his username and password, and the server uses his username and password to authenticate James.

Authorization is the process of deciding whether the authenticated user is allowed to perform an action on a specific resource (Web API Resource) or not. For example, James (who is an authenticated user) has the permission to get a resource but does not have the permission to create a resource.

Authentication in Web API

The Web API Service assumes that the authentication process should happen in the host Server and we generally host the Web API Service at IIS. The IIS Server uses the HTTP modules for checking the authentication of a user. You can configure your project to use any of the built-in authentication modules which are available in IIS or ASP.NET, or you can also create your own HTTP module to perform custom authentication.

When the host (IIS Server) authenticates the user, it generally creates a principal object (i.e. IPrincipal object) under which the code is going to run. So, once the Principal object (IPrincipal object) is created, then the host (i.e. IIS Server) attaches that principal object to the current thread by setting Thread.CurrentPrincipal

If you are confused at the moment about how the Principal object is created and how the principal object is attached to the current thread, then dont worry we will discuss all these things in greater detail in our upcoming Videos. In this Video, I am just going to give you an overview of how authentication and authorization happen in Web API services.

Understanding Principal Object

The Principal object contains two things one is the Identity object which actually contains the information about the user and the other one is the IsInRole property which is a boolean property and this property is set to true if the user is assigned with any roles else false. The following diagram shows the IPrincipal interface definition.

Authentication and Authorization in Web API - IPrincipal Object

Lets have a look at the Identity interface definition which contains the users information.

Authentication and Authorization in Web API - IIdentity Object

The Identity Object which is a property of Principal Object contains three properties i.e. Name (string type), AuthenticationType (string type), and IsAuthenticated (boolean type). If the user is authenticated, then the Identity.IsAuthenticated property will return true else false. The Name property of the Identity object will store the name of Identity, generally, identity is nothing but the logged-in username. Similarly, the AuthenticationType property returns the type of authentication used to identify the user.

The Identity interface is generally implemented by the GenericIdentity and WindowsIdentity classes. We will discuss how these classes implement the IIdentity interface in our upcoming Video.

HTTP Message Handlers for Authentication in Web API

Instead of using the host (i.e. IIS Server where the Web API service is hosted) for authentication, you can also write the authentication logic into a custom HTTP Message Handler. In that case, the HTTP Message Handler is going to check the incoming HTTP request for authenticating the user and then set the Principal Object.

Differences HTTP Message Handler over HTTP Module:

An HTTP Module sees all the incoming requests that go through the ASP.NET pipeline whereas a message handler only sees the incoming requests which are routed to the Web API Service.

It is also possible to select a specific HTTP Message Handler and then you can use that specific HTTP Message Handler for authentication for a specific route. The HTTP Modules are specific to IIS whereas the HTTP Message Handlers can be used with both web-hosting (within a server) and self-hosting (within an application).

The HTTP Modules participate in IIS logging, auditing, and so on. Generally, if you dont want to support self-hosting, then HTTP Module is a better option but if you want to support self-hosting then HTTP Message Handler is a better option.

Setting the Principal Object

If  you are going to implement your own custom logic for authenticating the user then you can set the principal object at two places which are as follows:

Thread.CurrentPrincipal. This is the standard way to set the threads principal in .NET.

HttpContext.Current.User. This property is specific to ASP.NET.

The following image shows how to create and set the principal object with the current thread. Here I am showing you both the options to set the Principal object.

Authentication and Authorization in Web API - Setting Principal Object

If you are going to host the Web API service in IIS, then you need to set the principal object in both places because of the security concerns i.e. security becomes inconsistent. In the case of Self-hosting the HttpContext.Current value is null. To ensure your code is host-agnostic (i.e. to support both web hosting and self-hosting), you need to check for null before assigning the Principal object to the HttpContext.Current as shown in the above image.

Authorization in Web API

The Authorization Process is going to happen before executing the Controller Action Method which provides you the flexibility to decide whether you want to grant access to that resource or not.

We can implement this in ASP.NET Web API by using the Authorization filters which will be executed before the controller action method executed. So, if the request is not authorized for that specific resource, then the filter returns an error response to the client without executing the controller action method. The following diagram explains the above.

Authentication and Authorization in Web API

Using the [Authorize] Attribute

The ASP.NET Web API Framework provides a built-in authorization filter attribute i.e. AuthorizeAttribute and you can use this built-in filter attribute to checks whether the user is authenticated or not. If not, then it simply returns the HTTP status code 401 Unauthorized, without invoking the controller action method.

You can apply the above built-in filter globally, at the controller level, or at the action level.

At Globally:

If you want to check the authentication for all the Web API controllers, then it is better to add the AuthorizeAttribute filter to the global filter list within the Register method of the WebApiConfig class as shown in the below image:

Authentication and Authorization in Web API - Applying Authorize Filter Globally

At Controller Level:

If you want to provide authentication for all the action methods of a specific controller, then it is better and recommended to add the Authorize filter at the controller level as shown in the below image.

Authentication and Authorization in Web API - At Controller Level

At Action Level:

If you want to provide authentication for specific action methods of a controller, then it is better to add the Authorize filter attribute to the action method which required authentication as shown in the below image.

Authentication and Authorization in Web API - At Action Level

Another way of doing this is, restrict the controller by decorating the controller with Authorize filter attribute and then allow anonymous access to the action methods which does not require authentication by using the AllowAnonymous attribute. In the below example, the Post method is restricted, but the Get method allows anonymous access.

Authentication and Authorization in Web API

As of now, we have discussed two things. If we want to check the authentication before invoking the action method then we need to use the built-in Authorize Filter Attribute. If we want any action method to be accessed by the anonymous users then we need to decorate that action method with the AllowAnonymous attribute. Along the way, we can also limit access to specific users or to users with specific roles.

Restrict by Users:

Authentication and Authorization in Web API - Restricted by Users

Restrict by Roles:

Authentication and Authorization in Web API - Restricted by Roles

Note: The point to remember here is that the AuthorizeAttribute filter for Web API is located in the System.Web.Http namespace. In MVC there is also an AuthorizeAttribute filter which is located in the System.Web.Mvc namespace, which is not compatible with Web API controllers.

Authorization Inside a Controller Action

In some scenarios, you might allow a request to proceed, but you need to change the behavior based on the principal. For example, the information that you are going to return from the action depends on the users role. Within a controller action method, you can get the current principal object from the ApiController.User property is shown in the below image.

Authentication and Authorization in Web API - Authorization within Controller

In the next Video, I will discuss how to implement ASP.NET Web API Basic Authentication with an example. Here, in this Video, I try to give you an overview of Authentication and Authorization in Web API. I hope this Video will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this Video. 


See All

Comments (555 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET Web API / Blog

What is ASP.NET Web API Application?

In this ASP.NET Web API Tutorials series, I covered all the features of ASP.NET Web API. You will learn from basic to advance level features of ASP.NET Web API. The term API stands for “Application Programming Interface” and ASP.NET Web API is a framework provided by Microsoft which makes it easy to build Web APIs, i.e. it is used to develop HTTP-based web services on the top of .NET Framework.
3-Feb-2022 /34 /555

ASP.NET Web API / Blog

How to creat ASP.NET Web API Application using Visual Studio?

In this article, I am going to discuss the step-by-step procedure for Creating ASP.NET Web API Application. Please read our previous article before proceeding to this article where we gave an overview of the ASP.NET Web API framework. As part of this article, we ate going to discuss the following pointers.
3-Feb-2022 /34 /555

ASP.NET Web API / Blog

How to add Swagger in Web API Application?

In this article, I am going to discuss how to add Swagger in Web API Application to document and test restful Web API services. Please read our previous article where we discussed How to Create an ASP.NET Web API Application step by step before proceeding to this article as we are going to work with the same example. As part of this article, we are going to discuss the following pointers.
3-Feb-2022 /34 /555