- ASP.NET Web API Security Essentials
- Rajesh Gunasundaram
- 222字
- 2021-07-30 10:15:54
Using the [Authorize] attribute
AuthorizeAttribute
will make sure if the user is authenticated or unauthenticated. Unauthorized error with HTTP status code 401 will be returned if the user is not authenticated and the corresponding action will not be invoked. Web API enables you to apply the filter in three ways. We can apply them at global level, or at the controller level, or at the individual action level.
Global authorization filter
To apply authorization filter for all Web API controllers, we need to add the AuthorizeAttribute
filter to the global filter list in the Global.asax
file as given below:
public static void Register(HttpConfiguration config) { config.Filters.Add(new AuthorizeAttribute()); }
Controller level authorization filter
To apply an authorization filter for a specific controller, we need to decorate the controller with filter attribute as given in the following code:
// Require authorization for all actions on the controller. [Authorize] public class ContactsController : ApiController { public IEnumerable<Contact> GetAllContacts() { ... } public IHttpActionResult GetContact(int id) { ... } }
Action level authorization filter
To apply an authorization filter for specific actions, we need to add the attribute to the action method as given in the following code:
public class ContactsController : ApiController { public IEnumerable<Contact> GetAllContacts() { ... } // Require authorization for a specific action. [Authorize] public IHttpActionResult GetContact(int id) { ... } }
- Go Web編程
- Learning C# by Developing Games with Unity 2020
- Java高手真經(jīng)(高級(jí)編程卷):Java Web高級(jí)開(kāi)發(fā)技術(shù)
- Practical Game Design
- GameMaker Programming By Example
- 零基礎(chǔ)學(xué)Python網(wǎng)絡(luò)爬蟲(chóng)案例實(shí)戰(zhàn)全流程詳解(高級(jí)進(jìn)階篇)
- 基于SpringBoot實(shí)現(xiàn):Java分布式中間件開(kāi)發(fā)入門與實(shí)戰(zhàn)
- Java并發(fā)編程:核心方法與框架
- Sails.js Essentials
- Android 游戲開(kāi)發(fā)大全(第二版)
- IBM RUP參考與認(rèn)證指南
- Developing Java Applications with Spring and Spring Boot
- Ionic3與CodePush初探:支持跨平臺(tái)與熱更新的App開(kāi)發(fā)技術(shù)
- Practical Time Series Analysis
- 趣學(xué)Python游戲編程