- 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) { ... } }
- 少兒人工智能趣味入門:Scratch 3.0動畫與游戲編程
- MySQL數據庫管理實戰
- 造個小程序:與微信一起干件正經事兒
- 架構不再難(全5冊)
- MySQL 8 DBA基礎教程
- 數據結構習題精解(C語言實現+微課視頻)
- Visual C++串口通信技術詳解(第2版)
- PySide GUI Application Development(Second Edition)
- 移動界面(Web/App)Photoshop UI設計十全大補
- C#實踐教程(第2版)
- 常用工具軟件立體化教程(微課版)
- Java Web開發就該這樣學
- OpenCV with Python Blueprints
- Python Web自動化測試設計與實現
- INSTANT Apache ServiceMix How-to