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
}
}
...and that is it
Recently I had to disable access to a certain functionality for everybody so I just put Authorization
attribute 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
}
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 Authorize
attribute 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 OverrideAuthorization
attribute 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
}
}
Top comments (0)