Take advantage of ASP.Net Web API authorization filters to authorize incoming requests to your web API Credit: Thinkstock Security is a major concern in web-based enterprise applications. When you need to transmit data over the wire, you should be aware of the various tools you can use to secure that data. ASP.Net Web API is a lightweight framework used for building stateless RESTful services that run on HTTP. One way to secure Web API services is with authorization filters. Ideally, you should perform authentication and authorization early in the Web API pipeline. This helps to eliminate unnecessary processing overhead from the request cycle. Note that, whether you use HTTP modules or HTTP message handlers for authentication, you can retrieve the current principal (i.e. the user) from the ApiController.User property. Also keep in mind that Web API authorization filters execute before the controller action methods. So if the incoming request is not authorized, an error will be returned from the service, the request will be ignored, and the action method of the service will not be executed. Using the AuthorizeAttribute authorization filter The built-in authorization filter AuthorizeAttribute can be used to authorize incoming requests. You can use AuthorizeAttribute to check whether the user is authenticated. If the user is not authenticated, it will return the HTTP status code 401. This authorization can be applied in Web API globally or at the controller level. Note that you can also implement a custom message handler to authorize access to your controller methods as message filters are executed much earlier in the Web API life cycle. To restrict access to all controllers, you can add the AuthorizeAttribute globally to the Filters collection of the HttpConfiguration instance. The following code snippet shows how you can add the AuthorizeAttribute to the Filters collection of the HttpConfiguration object. public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: “DefaultApi”, routeTemplate: “api/{controller}/{id}”, defaults: new { id = RouteParameter.Optional } ); config.Filters.Add(new AuthorizeAttribute()); } Using the Authorize attribute At the controller level, you can restrict access by applying the Authorize attribute as shown in the code snippet given next. [Authorize] public class EmployeesController : ApiController { //Write methods here that correspond to the Http verbs } You can also apply the Authorize attribute at the action level to restrict access to a particular action method. The following code snippet illustrates how this can be implemented. public class EmployeesController : ApiController { public HttpResponseMessage Get() { //Some code } // Require authorization for a specific action. [Authorize] public HttpResponseMessage Post(Employee emp) { //Some code } } In the code snippet shown earlier, access to the Post() method is restricted while access to the Get() method is not restricted. You can also restrict the controller and then provide anonymous access to one or more action methods. The code snippet that follows illustrates this. public class EmployeesController : ApiController { public HttpResponseMessage Get() { //Some code } [AllowAnonymous] public HttpResponseMessage Post(Employee emp) { //Some code } } Authorize actions by roles and users It is also possible to restrict access to action methods by roles and users. The following code snippet shows how this can be achieved. [Authorize(Users="Joydip,Jini")] //Restrict access by user public class EmployeesController : ApiController { //Write methods here that correspond to the Http verbs } In the above example, the Employees controller restricts access to the users Joydip and Jini only. The code below shows how you can restrict access by roles. [Authorize(Roles="Administrators")] //Restrict by roles public class EmployeesController : ApiController { //Write methods here that correspond to the Http verbs } You can always access the ApiController.User property inside the controller method to retrieve the current principle and grant authorization based on the user’s role. This is shown in the code listing below. public HttpResponseMessage Get() { if (User.IsInRole(“Administrators”)) { //Write your code here } } Using custom authorization filters in ASP.Net Web API An authorization filter is a class that extends the AuthorizationFilterAttribute class and overrides the OnAuthorization() method. This is the method where you can write the authorization logic. If the authorization fails you can return an instance of the UnauthorizedException class or even a custom HttpResponseMessage. The following code listing shows how you can implement a custom class for authorizing requests to your web API. Note that you should extend the AuthorizeAttribute class to implement your own authorization filter class. public class CustomAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { if (AuthorizeRequest(actionContext)) { return; } HandleUnauthorizedRequest(actionContext); } protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext) { //Code to handle unauthorized request } private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext) { //Write your code here to perform authorization return true; } } Related content how-to How to use FastEndpoints in ASP.NET Core Take advantage of the free open-source FastEndpoints library to build fast and lean APIs in your ASP.NET Core applications. By Joydip Kanjilal Jul 11, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks how-to How to use Refit to consume APIs in ASP.NET Core Take advantage of Refit REST library to simplify API consumption and make your code cleaner, more efficient, and easier to maintain. By Joydip Kanjilal Jul 04, 2024 10 mins C# Microsoft .NET Software Deployment how-to When to use an abstract class vs. interface in C# Understanding the differences between an abstract class and interface is key to designing loosely coupled and extensible applications. By Joydip Kanjilal Jun 20, 2024 10 mins Small and Medium Business Microsoft .NET C# how-to 6 security best practices for ASP.NET Core Learn the best practices and built-in safeguards for preventing attacks and protecting sensitive data in your ASP.NET Core web applications. By Joydip Kanjilal Jun 07, 2024 6 mins C# Microsoft .NET Web Development Resources Videos