- 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) { ... } }
- Unreal Engine Physics Essentials
- 程序員面試白皮書
- 編程卓越之道(卷3):軟件工程化
- 區塊鏈架構與實現:Cosmos詳解
- 秒懂設計模式
- 網店設計看這本就夠了
- Python漫游數學王國:高等數學、線性代數、數理統計及運籌學
- 可解釋機器學習:模型、方法與實踐
- AppInventor實踐教程:Android智能應用開發前傳
- 精通Python自動化編程
- Odoo 10 Implementation Cookbook
- 跟戴銘學iOS編程:理順核心知識點
- 深度實踐KVM:核心技術、管理運維、性能優化與項目實施
- Getting Started with Electronic Projects
- MATLAB 2020 GUI程序設計從入門到精通