Authentication and Authorization in ASP.NET Web API (2024)

  • Article

by Rick Anderson

You've created a web API, but now you want to control access to it. In this series of articles, we'll look at some options for securing a web API from unauthorized users. This series will cover both authentication and authorization.

  • Authentication is knowing the identity of the user. For example, Alice logs in with her username and password, and the server uses the password to authenticate Alice.
  • Authorization is deciding whether a user is allowed to perform an action. For example, Alice has permission to get a resource but not create a resource.

The first article in the series gives a general overview of authentication and authorization in ASP.NET Web API. Other topics describe common authentication scenarios for Web API.

Note

Thanks to the people who reviewed this series and provided valuable feedback: Rick Anderson, Levi Broderick, Barry Dorrans, Tom Dykstra, Hongmei Ge, David Matson, Daniel Roth, Tim Teebken.

Authentication

Web API assumes that authentication happens in the host. For web-hosting, the host is IIS, which uses HTTP modules for authentication. You can configure your project to use any of the authentication modules built in to IIS or ASP.NET, or write your own HTTP module to perform custom authentication.

When the host authenticates the user, it creates a principal, which is an IPrincipal object that represents the security context under which code is running. The host attaches the principal to the current thread by setting Thread.CurrentPrincipal. The principal contains an associated Identity object that contains information about the user. If the user is authenticated, the Identity.IsAuthenticated property returns true. For anonymous requests, IsAuthenticated returns false. For more information about principals, see Role-Based Security.

HTTP Message Handlers for Authentication

Instead of using the host for authentication, you can put authentication logic into an HTTP message handler. In that case, the message handler examines the HTTP request and sets the principal.

When should you use message handlers for authentication? Here are some tradeoffs:

  • An HTTP module sees all requests that go through the ASP.NET pipeline. A message handler only sees requests that are routed to Web API.
  • You can set per-route message handlers, which lets you apply an authentication scheme to a specific route.
  • HTTP modules are specific to IIS. Message handlers are host-agnostic, so they can be used with both web-hosting and self-hosting.
  • HTTP modules participate in IIS logging, auditing, and so on.
  • HTTP modules run earlier in the pipeline. If you handle authentication in a message handler, the principal does not get set until the handler runs. Moreover, the principal reverts back to the previous principal when the response leaves the message handler.

Generally, if you don't need to support self-hosting, an HTTP module is a better option. If you need to support self-hosting, consider a message handler.

Setting the Principal

If your application performs any custom authentication logic, you must set the principal on two places:

  • Thread.CurrentPrincipal. This property is the standard way to set the thread's principal in .NET.
  • HttpContext.Current.User. This property is specific to ASP.NET.

The following code shows how to set the principal:

private void SetPrincipal(IPrincipal principal){ Thread.CurrentPrincipal = principal; if (HttpContext.Current != null) { HttpContext.Current.User = principal; }}

For web-hosting, you must set the principal in both places; otherwise the security context may become inconsistent. For self-hosting, however, HttpContext.Current is null. To ensure your code is host-agnostic, therefore, check for null before assigning to HttpContext.Current, as shown.

Authorization

Authorization happens later in the pipeline, closer to the controller. That lets you make more granular choices when you grant access to resources.

  • Authorization filters run before the controller action. If the request is not authorized, the filter returns an error response, and the action is not invoked.
  • Within a controller action, you can get the current principal from the ApiController.User property. For example, you might filter a list of resources based on the user name, returning only those resources that belong to that user.

Authentication and Authorization in ASP.NET Web API (1)

Using the [Authorize] Attribute

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action.

You can apply the filter globally, at the controller level, or at the level of individual actions.

Globally: To restrict access for every Web API controller, add the AuthorizeAttribute filter to the global filter list:

public static void Register(HttpConfiguration config){ config.Filters.Add(new AuthorizeAttribute());}

Controller: To restrict access for a specific controller, add the filter as an attribute to the controller:

// Require authorization for all actions on the controller.[Authorize]public class ValuesController : ApiController{ public HttpResponseMessage Get(int id) { ... } public HttpResponseMessage Post() { ... }}

Action: To restrict access for specific actions, add the attribute to the action method:

public class ValuesController : ApiController{ public HttpResponseMessage Get() { ... } // Require authorization for a specific action. [Authorize] public HttpResponseMessage Post() { ... }}

Alternatively, you can restrict the controller and then allow anonymous access to specific actions, by using the [AllowAnonymous] attribute. In the following example, the Post method is restricted, but the Get method allows anonymous access.

[Authorize]public class ValuesController : ApiController{ [AllowAnonymous] public HttpResponseMessage Get() { ... } public HttpResponseMessage Post() { ... }}

In the previous examples, the filter allows any authenticated user to access the restricted methods; only anonymous users are kept out. You can also limit access to specific users or to users in specific roles:

// Restrict by user:[Authorize(Users="Alice,Bob")]public class ValuesController : ApiController{} // Restrict by role:[Authorize(Roles="Administrators")]public class ValuesController : ApiController{}

Note

The AuthorizeAttribute filter for Web API controllers is located in the System.Web.Http namespace. There is a similar filter for MVC controllers in the System.Web.Mvc namespace, which is not compatible with Web API controllers.

Custom Authorization Filters

To write a custom authorization filter, derive from one of these types:

  • AuthorizeAttribute. Extend this class to perform authorization logic based on the current user and the user's roles.
  • AuthorizationFilterAttribute. Extend this class to perform synchronous authorization logic that is not necessarily based on the current user or role.
  • IAuthorizationFilter. Implement this interface to perform asynchronous authorization logic; for example, if your authorization logic makes asynchronous I/O or network calls. (If your authorization logic is CPU-bound, it is simpler to derive from AuthorizationFilterAttribute, because then you don't need to write an asynchronous method.)

The following diagram shows the class hierarchy for the AuthorizeAttribute class.

Authentication and Authorization in ASP.NET Web API (2)

Diagram of the class hierarchy for the Authorize Attribute class. Authorize Attribute is at the bottom, with an arrow pointing up to Authorization Filter Attribute, and an arrow pointing up to I Authorization Filter at the top.

Authorization Inside a Controller Action

In some cases, you might allow a request to proceed, but change the behavior based on the principal. For example, the information that you return might change depending on the user's role. Within a controller method, you can get the current principal from the ApiController.User property.

public HttpResponseMessage Get(){ if (User.IsInRole("Administrators")) { // ... }}
Authentication and Authorization in ASP.NET Web API (2024)

FAQs

How to achieve authentication and authorization in asp net? ›

1. Form Authentication
  1. When a user requests a page for the application, ASP.NET checks session cookie. ...
  2. If session cookies does not exists or not valid then it redirect to login form.
  3. User will enter username and password and if they are valid then he will get authenticated and authorized.

How do you handle authentication and authorization in API? ›

To use an API that requires key-based authentication, the user or application includes the API key as a parameter in the request, typically as a query parameter or in a header. The API provider verifies the key and then allows or denies access to the API based on the user's permissions and the API's usage limits.

What is the difference between authentication and authorization in Web API? ›

Authentication is used to verify that users really are who they represent themselves to be. Once this has been confirmed, authorization is then used to grant the user permission to access different levels of information and perform specific functions, depending on the rules established for different types of users.

How to authenticate Web API in asp net? ›

Token-Based Authentication operates as follows:
  1. The user inserts his credentials (i.e., username and password) into the client (here, the client refers to the browser or mobile device, for example).
  2. After that, the client sends these credentials (username and password) to the Authorization Server.
Mar 29, 2024

Which authentication is best for Web API? ›

Best API authentication protocols
  1. OAuth (Open Authorization) OAuth is an industry-standard authentication protocol that allows secure access to resources on behalf of a user or application. ...
  2. Bearer tokens. Bearer tokens are a simple way to authenticate API requests. ...
  3. API keys. ...
  4. JSON Web Tokens (JWT) ...
  5. Basic authentication.
Oct 25, 2023

How to implement authentication and authorization in .NET Core Web API? ›

  1. var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method. POST); request. ...
  2. HttpResponse<String> response = Unirest. ...
  3. import http. ...
  4. require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/oauth/token") http = Net::HTTP.

How to authenticate rest API in C#? ›

Here we go!
  1. Step 1 : New Project. Open Visual Studio and select New Project. ...
  2. Step 2: Select the “Web API” Template. Select the “Web API” Template. ...
  3. Step 3: Click “Change Authentication”
  4. Step 4: Select Windows Authentication. ...
  5. Step 5 – Edit the “Index” Method of the “Values” Controller. ...
  6. Step 6 – Build.
Feb 17, 2019

How is authentication done in the rest API? ›

4 methods for REST API authentication
  1. API keys as headers. First, we have API authentication via HTTP headers. ...
  2. API keys as query parameters. Alternatively, some vendors will ask us to provide authentication details as API parameters. ...
  3. Basic auth. ...
  4. Bearer tokens.
Jul 21, 2023

How is authentication done in web API? ›

Web API assumes that authentication happens in the host. For web-hosting, the host is IIS, which uses HTTP modules for authentication. You can configure your project to use any of the authentication modules built in to IIS or ASP.NET, or write your own HTTP module to perform custom authentication.

How to secure an API without authentication? ›

API Without Authentication: Risks and Solutions
  1. Implement Strong Authentication Methods.
  2. Enforce Role-Based Access Controls (RBAC)
  3. Implement Multi-Factor Authentication (MFA)
  4. Encrypt Sensitive Data.
  5. Monitor and Log API Activities.
  6. Regularly Update and Patch APIs.
Jan 3, 2024

How to implement basic authentication in ASP.NET Web API? ›

In IIS Manager, go to Features View, select Authentication, and enable Basic authentication. In your Web API project, add the [Authorize] attribute for any controller actions that need authentication. A client authenticates itself by setting the Authorization header in the request.

What is authentication and authorization in ASP.NET with example? ›

Authentication is the process of determining a user's identity. Authorization is the process of determining whether a user has access to a resource. In ASP.NET Core, authentication is handled by the authentication service, IAuthenticationService, which is used by authentication middleware.

What is an example of authentication and authorization? ›

In simple terms, authentication is the process of verifying who a user is, while authorization is the process of verifying what they have access to. Comparing these processes to a real-world example, when you go through security in an airport, you show your ID to authenticate your identity.

How authentication works in .NET Core Web API? ›

Authentication service on the server side of the web application is responsible to verify the user's identity and provide him access. There are three primary tasks involved in the process of authentication, Users provide their credentials. Server verifies the provided credentials.

How to secure ASP.NET Web API? ›

Web API Security Best Practices
  1. Data Encryption through TLS. Security starts right from establishing an HTTP connection. ...
  2. Access Control. ...
  3. Throttling and Quotas. ...
  4. Sensitive Information in the API Communication. ...
  5. Remove Unnecessary Information. ...
  6. Using Hashed Passwords. ...
  7. Data Validation.
Sep 20, 2021

How do you ensure authentication in an ASP.NET project? ›

Add authentication middleware

Add the UseAuthentication middleware after UseRouting in the Configure method in the Startup file. This will enable us to authenticate using ASP.NET Core Identity. With all of this in place, the application Is all set to start using Identity.

How do you implement user authentication and authorization? ›

It involves enforcing access control policies based on the authenticated identity and associated permissions which can be implemented using techniques such as Role-Based Access Control (RBAC) , Attribute-Based Access Control (ABAC) , Policy-Based Access Control or Claims-Based Authorization.

How to implement authentication and authorization in ASP.NET MVC? ›

Authentication and authorization using ASP.NET MVC
  1. Step1: Select ASP.NET Web Application (.NET Framework)
  2. Step2: Type project and solution name. ...
  3. Step 3: Select project template. ...
  4. Step 4: Change web.config file. ...
  5. Step 5: Add some model and view model class. ...
  6. Step 6: Add Controllers to the application.
Dec 5, 2020

How authentication and authorization works in ASP.NET MVC? ›

A user is authenticated by its identity and assigned roles to a user determine about authorization or permission to access resources. ASP.NET provides IPrincipal and identity interfaces to represent the identity and role of a user.

Top Articles
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 6352

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.