- 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) { ... } }
- Getting Started with Gulp(Second Edition)
- Vue.js設(shè)計(jì)與實(shí)現(xiàn)
- JavaScript修煉之道
- Java 9 Concurrency Cookbook(Second Edition)
- 劍指JVM:虛擬機(jī)實(shí)踐與性能調(diào)優(yōu)
- 深入淺出Prometheus:原理、應(yīng)用、源碼與拓展詳解
- 編程珠璣(續(xù))
- Java加密與解密的藝術(shù)(第2版)
- 概率成形編碼調(diào)制技術(shù)理論及應(yīng)用
- Hands-On Microservices with Kotlin
- Hands-On Full Stack Development with Spring Boot 2.0 and React
- App Inventor 2 Essentials
- Java EE Web應(yīng)用開發(fā)基礎(chǔ)
- Python硬件編程實(shí)戰(zhàn)
- 百萬在線:大型游戲服務(wù)端開發(fā)