DEV Community

Cover image for C# Authorization attribute and how to override it
Senad Meškin
Senad Meškin

Posted on

C# Authorization attribute and how to override it

Disabling or enabling certain actions or endpoints in your controllers/API is relatively easy to do in ASP.NET, all you need is to add Authorize attribute to a Controller or Action with the desired roles and you are done.

[Authorize] // Only authenticated users will be able to access this controller
public class MyController : BaseController {
  [AllowAnonymous] //anyone can access this action, controller [Authorize] attribute is ignored
  public ActionResult AnyoneCanAccessIt(){
     //...code
  }
  [Authorize(Roles="Admin,QA")]
  public ActionResult Only_Role_Admin_and_QA_Can_Access_This(){
    //...code
  }
  public ActionResult All_Authenticated_Users_Can_Access_This_Action(){
   //...code
  }
}
Enter fullscreen mode Exit fullscreen mode

...and that is it

Recently I had to disable access to a certain functionality for everybody so I just put Authorizationattribute with an unexisting role at the controller and the problem was solved, at least I thought so.

[Authorize(Roles="Not allowed")]
/* access to this controller is restricted to all users without this role. 
We don't have this role in our system so no one can access it.
*/
public class MyController : BaseController {
   //.. bunch of actions
}
Enter fullscreen mode Exit fullscreen mode

But I forgot that there is only one method that needs to stay accessible to all authorized customers. One solution was to remove Authorize attributes from the controller and then disable access to each action individually by applying Authorizeattribute to each of them. That was a lot of work so I needed to find a different solution!
The best solution for this kind of problem is OverrideAuthorization attribute which removes any previously set Authorize logic and starts from the beginning.

All I needed to do is Add OverrideAuthorizationattribute to the action I want to be accessible, and then below it set Authorize attribute again.

[Authorize(Roles="Not allowed")]
/* access to this controller is restricted to all users without this role. 
We don't have this role in our system so no one can access it.
*/
public class MyController : BaseController {
   //.. bunch of actions

  [OverrideAuthorization] // overrides authorization filters defined at a higher level
  [Authorize] // will make this action only accessible to authenticated users
  public ActionResult My_Action_That_Needs_Access_Afterall(){
    //... code
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)