How can I manually check the url authorization in MVC5?
Two options,
Either use the "Roles" option under Authorize
like so:
[Authorize(Roles="TestUsers,Admins")]
And then add the users that should be allowed access to this action to those roles. Roles are provided as part of the ClaimsPrincipal
used by ASP Identity.
Or alternatively, provide your own implementation of the Authorize
attribute that tests the currently logged in user for whatever business rules you have and then either allow or disallow access.
Q: How can I manually validate in my AuthController if the logged in user is authorized to redirect to the MainController?
Since you are using Authorize
attribute, you don't need to check authorization manually in the action. These are some rules:
- Limit access to Authenticated users:
[Authorize]
- Limit access to some specific users:
[Authorize(Users="User1,User2")]
- Limit access to some specific roles:
[Authorize(Roles="Administrators,PowerUsers")]
Since you decorated the MainController
with Authorize
attribute, it means no one can access its actions without login.
So in Logon
action you don't need to check if the user is authorized to redirect to main controller. There isn't any security flaw here and you don't need to worry about authorization when you use RedirectToAction("Index", "Main")
.
Q: A definition in the the Authorize attribute would not solve the problem. How can Administrators restrict users and groups when they buy the software? Thy have no access to the code.
Roles are created for such requirement. You should use [Authorize(Roles="Role1")]
above MainController
and then each user of Role1
can access the actions of main controller. It can simply be done in user and role management of your application. So:
- At development time, decorate controllers and actions with static roles
- At run-time, you can manage user role using your application.
Note
In most applications roles are static and you can say which role can have access to which action. In such cases the current Authorize
attribute would be enough for authorization. Just add users to roles at run-time. Identity Samples contains required models, views and controllers to do so.
In a case which you want to create new roles at run-time or change permissions of a role at run-time, you need to create a new Authorize
attribute which reads role of user from a config file or database and also read permissions of a role from a config file or database and decide about authorization.