What is the use of Authorize Attribute in C# Asp.Net webAPI?

CsharpServer Side ProgrammingProgramming

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, having the permission to get data and post data is a part of authorization. The Authorization Process happens before executing the Controller Action Method which provides you the flexibility to decide whether we want to grant access to that resource or not.

In ASP.NET Web API authorization is implemented by using the Authorization filters which will be executed before the controller action method executed. 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.

We 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 StudentsController: 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 StudentsController : ApiController{
   public HttpResponseMessage Get() { ... }
   // Require authorization for a specific action.
   [Authorize]
   public HttpResponseMessage Post() { ... }
}

Example

using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      [Authorize]
      public IHttpActionResult Get(){
         return Ok();
      }
   }
}

Since we have added the authorize attribute over the action method, proper authorization like bearer token, API key, OAuth etc., should be used to access the action method. Unauthorized access will result in 401 Unauthorized response which is shown below.

raja
Published on 24-Sep-2020 11:24:16
Advertisements