Home > Article > Backend Development > What is the use of authorization attribute in C# Asp.Net webAPI?
Authorization is the process of deciding whether an authenticated user is allowed to perform an operation Whether to perform an operation on a specific resource (Web API resource). For example, Having permission to obtain and publish data is part of authorization. this The authorization process occurs before executing the controller action method Give you flexibility in deciding whether we want to grant access to the resource or not.
In ASP.NET Web API, authorization is achieved by using authorization filters It will be executed before the controller action method is executed. Web API Provides built-in authorization filter AuthorizeAttribute. This filter checks Whether the user is authenticated. If not, HTTP status code 401 is returned (Unauthorized), no action required.
We can apply filters globally, controller level or individual level operate.
To limit access to each Web API controller, add the AuthorizeAttribute filter to Global filter list.
public static void Register(HttpConfiguration config){ config.Filters.Add(new AuthorizeAttribute()); }
To restrict access to a specific controller, add the filter as an attribute to controller.
//All operations on the controller require authorization. [Authorization]
public class StudentsController: ApiController{ public HttpResponseMessage Get(int id) { ... } public HttpResponseMessage Post() { ... } }
To restrict access to a specific operation, add this attribute to the action method.
public class StudentsController : ApiController{ public HttpResponseMessage Get() { ... } // Require authorization for a specific action. [Authorize] public HttpResponseMessage Post() { ... } }
using System.Web.Http; namespace DemoWebApplication.Controllers{ public class DemoController : ApiController{ [Authorize] public IHttpActionResult Get(){ return Ok(); } } }
Since we added the authorization attribute on the action method, the action method should be accessed using appropriate authorization (such as bearer token, API key, OAuth, etc.) . Unauthorized access will result in a 401 Unauthorized response as shown below.
The above is the detailed content of What is the use of authorization attribute in C# Asp.Net webAPI?. For more information, please follow other related articles on the PHP Chinese website!