Home  >  Article  >  Backend Development  >  What is the use of authorization attribute in C# Asp.Net webAPI?

What is the use of authorization attribute in C# Asp.Net webAPI?

王林
王林forward
2023-08-25 23:37:081348browse

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.

Global

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());
}

Controller

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() { ... }
}

Operation

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() { ... }
}

Example

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.

C# Asp.Net webAPI 中的授权属性有什么用?

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Key-value pairs in C#Next article:Key-value pairs in C#