As I am new to ASP.NET Identity, I was going through a video on MVA when Jeremy Foster asked a question when demoing that how can the following be made dynamic:
[Authorize("Administrators, Users")]
public ActionResult SomeAction()
{
//Access to only admins and users
}
In answer, Adam Tuliper said it could be done using Claims somehow but I am not finding anything concrete on the Internet or I might not be understanding. But I would appreciate if somebody could show me how this can be done.
This is important because later on, I might want to allow SomeAction
to be accessed by another Role and if I need to re-compile and deploy my application for that everytime then that is not good. Also I might give the control to users to change access for other types of users.
In the past I have done this by overriding Authorize
attribute where I extract from cookie the user's RoleId and check from the database whether the user has access to the action being requested. But not sure how it can be done using Claims.
What about something like this: You could use it with a database, or simply maintain a list of authorized roles in the web.config.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MyCustomAuthorizationAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// Do some logic here to pull authorised roles from backing store (AppSettings, MSSQL, MySQL, MongoDB etc)
...
// Check that the user belongs to one or more of these roles
bool isUserAuthorized = ....;
if(isUserAuthorized)
return true;
return base.AuthorizeCore(httpContext);
}
}