2399total visits.
A major challenge in any web application is implementing its security.
In traditional web development with ASP.NET (from version 2.0 onwards), we have been using Membership and Role providers. These providers allow us to define Roles, Users and assign roles to users which helps us to manage Authorization.
ASP.NET Identity is the new membership system for building ASP.NET web applications, phone, store, or hybrid applications using social identities for authentication and authorization.
Authorize Attribute
In ASP.NET MVC, any incoming request is bound to a controller/method pair and served. This means that once the request matches a supported route and is resolved to controller and method, it gets executed no matter what.
In ASP.NET MVC, Authorize attribute is responsible for allowing access to Invoke Methods and Controllers only to known users.
Authorize attribute can be implemented on two levels.
- Controller Level
- Method/Action Level
Just adding [Authorize] keyword above controller or method checks users whether the user is responsible has access to invoke Controller and Methods.
1. Authorization at Controller Level
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
[Authorize] //Just checks whetehe the use is logged in or no [Authorize] //Checks at User Role Level, only permits if use is in specified Role [Authorize(Roles = "Admin")] //Authorization at User Level, only permists to these users [Authorize(Users = "aryalnishan@test.com, nishanaryal@test.com")] public class ManageUserController { public ActionResult ListUsers() { var data = db.Users.ToList(); return View(data); } } |
2. Authorization at Action/Method Level
|
1 2 3 4 5 6 7 8 9 10 11 12 |
//Just checks whether the user is logged in or no [Authorize] [Authorize] //Checks at User Role Level, only permits if use is in specified Role [Authorize(Roles = "Admin")] //Authorization at User Level, only permists to these users [Authorize(Users = "aryalnishan@test.com, nishanaryal@test.com")] public ActionResult Index() { return View(); } |
The [Authorize] attribute supports a couple of parameters through which developers can restrict the execution of the action method only to certain usernames and/or users with a given role. Here’s an example:
[Authorize(Roles=“Admin”, Users=“aryalnishan@test.com, nishanaryal@test.com”)]