- 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) { ... } }
- OpenDaylight Cookbook
- Spring Boot+Spring Cloud+Vue+Element項目實戰:手把手教你開發權限管理系統
- 區塊鏈:以太坊DApp開發實戰
- Mastering Yii
- Learning Laravel 4 Application Development
- PhpStorm Cookbook
- 微信小程序項目開發實戰
- 精通MATLAB(第3版)
- Mastering ROS for Robotics Programming
- Python極簡講義:一本書入門數據分析與機器學習
- C++反匯編與逆向分析技術揭秘(第2版)
- 網絡數據采集技術:Java網絡爬蟲實戰
- C Primer Plus(第6版)中文版【最新修訂版】
- 例說FPGA:可直接用于工程項目的第一手經驗
- 一覽眾山小:ASP.NET Web開發修行實錄