When standard types of authentication do not meet your requirements, you need to modify an authentication mechanism to create a custom solution. A user context has principal which represents the identity and roles for that user. A user is authenticated by its identity and assigned roles to a user determine about authorization or permission to access resources.
ASP.NET provides IPrincipal and IIdentity interfaces to represents the identity and role for a user. You can create a custom solution by evaluating the IPrincipal and IIdentity interfaces which are bound to the HttpContext as well as the current thread.
- public class CustomPrincipal : IPrincipal
- {
- public IIdentity Identity { get; private set; }
- public bool IsInRole(string role)
- {
- if (roles.Any(r => role.Contains(r)))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- public CustomPrincipal(string Username)
- {
- this.Identity = new GenericIdentity(Username);
- }
- public int UserId { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string[] roles { get; set; }
- }
Now you can put this CustomPrincipal objects into the thread’s currentPrinciple property and into the HttpContext’s User property to accomplish your custom authentication and authorization process.
ASP.NET Forms Authentication
ASP.NET forms authentication occurs after IIS authentication is completed. You can configure forms authentication by using forms element with in web.config file of your application. The default attribute values for forms authentication are shown below:
<system.web>
<authentication mode="Forms"> <forms loginUrl="Login.aspx" protection="All" timeout="30" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="default.aspx" cookieless="UseDeviceProfile" enableCrossAppRedirects="false" /> </authentication></system.web>
The FormsAuthentication class creates the authentication cookie automatically when SetAuthCookie() or RedirectFromLoginPage() methods are called. The value of authentication cookie contains a string representation of the encrypted and signed FormsAuthenticationTicket object.
You can create the FormsAuthenticationTicket object by specifying the cookie name, version of the cookie, directory path, issue date of the cookie, expiration date of the cookie, whether the cookie should be persisted, and optionally user-defined data as shown below:
- FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
- "userName",
- DateTime.Now,
- DateTime.Now.AddMinutes(30), // value of time out property
- false, // Value of IsPersistent property
- String.Empty,
- FormsAuthentication.FormsCookiePath);
Now, you can encrypt this ticket by using the Encrypt method FormsAuthentication class as given below:
- string encryptedTicket = FormsAuthentication.Encrypt(ticket);
Note
To encrypt FormsAuthenticationTicket ticket set the protection attribute of the forms element to All or Encryption.
Custom Authorization
ASP.NET MVC provides Authorization filter to authorize a user. This filter can be applied to an action, a controller, or even globally. This filter is based on AuthorizeAttribute class. You can customize this filter by overriding OnAuthorization() method as shown below:
- public class CustomAuthorizeAttribute : AuthorizeAttribute
- {
- public string UsersConfigKey { get; set; }
- public string RolesConfigKey { get; set; }
- protected virtual CustomPrincipal CurrentUser
- {
- get { return HttpContext.Current.User as CustomPrincipal; }
- }
- public override void OnAuthorization(AuthorizationContext filterContext)
- {
- if (filterContext.HttpContext.Request.IsAuthenticated)
- {
- var authorizedUsers = ConfigurationManager.AppSettings[UsersConfigKey];
- var authorizedRoles = ConfigurationManager.AppSettings[RolesConfigKey];
- Users = String.IsNullOrEmpty(Users) ? authorizedUsers : Users;
- Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles : Roles;
- if (!String.IsNullOrEmpty(Roles))
- {
- if (!CurrentUser.IsInRole(Roles))
- {
- filterContext.Result = new RedirectToRouteResult(new
- RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
- // base.OnAuthorization(filterContext); //returns to login url
- }
- }
- if (!String.IsNullOrEmpty(Users))
- {
- if (!Users.Contains(CurrentUser.UserId.ToString()))
- {
- filterContext.Result = new RedirectToRouteResult(new
- RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
- // base.OnAuthorization(filterContext); //returns to login url
- }
- }
- }
- }
- }
User Authentication
A user will be authenticated if IsAuthenticated property returns true. For authenticating a user you can use one of the following two ways:
- Thread.CurrentPrincipal.Identity.IsAuthenticated
- HttpContext.Current.User.Identity.IsAuthenticated
Designing Data Model
Now it’s time to create data access model classes for creating and accessing Users and Roles as shown below:
- public class User
- {
- public int UserId { get; set; }
- [Required]
- public String Username { get; set; }
- [Required]
- public String Email { get; set; }
- [Required]
- public String Password { get; set; }
- public String FirstName { get; set; }
- public String LastName { get; set; }
- public Boolean IsActive { get; set; }
- public DateTime CreateDate { get; set; }
- public virtual ICollection<Role> Roles { get; set; }
- }
- public class Role
- {
- public int RoleId { get; set; }
- [Required]
- public string RoleName { get; set; }
- public string Description { get; set; }
- public virtual ICollection<User> Users { get; set; }
- }
Defining Database Context with code first mapping between User and Role
Using Entity Framework code first approach, create a DataContext having User and Role entities with its relational mapping details as shown below:
- public class DataContext : DbContext
- {
- public DataContext()
- : base("DefaultConnection")
- {
- }
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- modelBuilder.Entity<User>()
- .HasMany(u => u.Roles)
- .WithMany(r=>r.Users)
- .Map(m =>
- {
- m.ToTable("UserRoles");
- m.MapLeftKey("UserId");
- m.MapRightKey("RoleId");
- });
- }
- public DbSet<User> Users { get; set; }
- public DbSet<Role> Roles { get; set; }
- }
Code First Database Migrations
With the help of entity framework code first database migrations create the database named as Security in the SQL Server. Run the following command through Visual Studio Package Manager Console to migrate your code into SQL Server database.
After running first command i.e. enabling migrations for your project, add seed data to Configuration.cs file of Migrations folder as shown below:
User user1 = new User { Username = "admin", Email = "[email protected]", FirstName = "Admin", Password = "123456", IsActive = true, CreateDate = DateTime.UtcNow, Roles = new List<role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">()</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">};</span></role>
<role style="BOX-SIZING: border-box"></role>
<role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">User</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> user2 </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,0,128); VERTICAL-ALIGN: top" class="kwd">new</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">User</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">{</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Username</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,104,32); VERTICAL-ALIGN: top" class="str">"user1"</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">,</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Email</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,104,32); VERTICAL-ALIGN: top" class="str">"[email protected]"</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">,</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">FirstName</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,104,32); VERTICAL-ALIGN: top" class="str">"User1"</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">,</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Password</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,104,32); VERTICAL-ALIGN: top" class="str">"123456"</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">,</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">IsActive</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,0,128); VERTICAL-ALIGN: top" class="kwd">true</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">,</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">CreateDate</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">DateTime</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">UtcNow</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">,</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Roles</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,0,128); VERTICAL-ALIGN: top" class="kwd">new</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">List</span><role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">()</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">};</span></role></role>
<role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"></role></role>
<role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> user1</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Roles</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Add</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">(</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln">role1</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">);</span></role></role>
<role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> user2</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Roles</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Add</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">(</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln">role2</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">);</span></role></role>
<role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"></role></role>
<role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> context</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Users</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Add</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">(</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln">user1</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">);</span></role></role>
<role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> context</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Users</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Add</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">(</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln">user2</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">);</span></role></role>
<role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">}</span></role></role>
Solution Structure
Designing View Model
Create a view model class for handing login process as given below:
1. public class LoginViewModel
2. {
3. [Required]
4. [Display(Name = "User name")]
5. public string Username { get; set; }
6.
7. [Required]
8. [DataType(DataType.Password)]
9. [Display(Name = "Password")]
10. public string Password { get; set; }
11.
12. [Display(Name = "Remember me?")]
13. public bool RememberMe { get; set; }
14. }
1. public class CustomPrincipalSerializeModel
2. {
3. public int UserId { get; set; }
4. public string FirstName { get; set; }
5. public string LastName { get; set; }
6. public string[] roles { get; set; }
7. }
Forms Authentication Initialization
1. public class AccountController : Controller
2. {
3. DataContext Context = new DataContext();
4. //
5. // GET: /Account/
6. public ActionResult Index()
7. {
8. return View();
9. }
10.
11. [HttpPost]
12. public ActionResult Index(LoginViewModel model, string returnUrl = "")
13. {
14. if (ModelState.IsValid)
15. {
16. var user = Context.Users.Where(u => u.Username == model.Username && u.Password == model.Password).FirstOrDefault();
17. if (user != null)
18. {
19. var roles=user.Roles.Select(m => m.RoleName).ToArray();
20.
21. CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
22. serializeModel.UserId = user.UserId;
23. serializeModel.FirstName = user.FirstName;
24. serializeModel.LastName = user.LastName;
25. serializeModel.roles = roles;
26.
27. string userData = JsonConvert.SerializeObject(serializeModel);
28. FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
29. 1,
30. user.Email,
31. DateTime.Now,
32. DateTime.Now.AddMinutes(15),
33. false,
34. userData);
35.
36. string encTicket = FormsAuthentication.Encrypt(authTicket);
37. HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
38. Response.Cookies.Add(faCookie);
39.
40. if(roles.Contains("Admin"))
41. {
42. return RedirectToAction("Index", "Admin");
43. }
44. else if (roles.Contains("User"))
45. {
46. return RedirectToAction("Index", "User");
47. }
48. else
49. {
50. return RedirectToAction("Index", "Home");
51. }
52. }
53.
54. ModelState.AddModelError("", "Incorrect username and/or password");
55. }
56.
57. return View(model);
58. }
59.
60. [AllowAnonymous]
61. public ActionResult LogOut()
62. {
63. FormsAuthentication.SignOut();
64. return RedirectToAction("Login", "Account", null);
65. }
66. }
1. public class MvcApplication : System.Web.HttpApplication
2. {
3. protected void Application_Start()
4. {
5. AreaRegistration.RegisterAllAreas();
6.
7. WebApiConfig.Register(GlobalConfiguration.Configuration);
8. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
9. RouteConfig.RegisterRoutes(RouteTable.Routes);
10. BundleConfig.RegisterBundles(BundleTable.Bundles);
11.
12. Database.SetInitializer<DataContext>(new DataContextInitilizer());
13. }
14. protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
15. {
16. HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
17. if (authCookie != null)
18. {
19.
20. FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
21.
22. CustomPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject<CustomPrincipalSerializeModel>(authTicket.UserData);
23. CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
24. newUser.UserId = serializeModel.UserId;
25. newUser.FirstName = serializeModel.FirstName;
26. newUser.LastName = serializeModel.LastName;
27. newUser.roles = serializeModel.roles;
28.
29. HttpContext.Current.User = newUser;
30. }
31.
32. }
33. }
Base Controller for accessing Current User
Create a base controller for accessing your User data in your all controller. Inherit, your all controller from this base controller to access user information from the UserContext.
1. public class BaseController : Controller
2. {
3. protected virtual new CustomPrincipal User
4. {
5. get { return HttpContext.User as CustomPrincipal; }
6. }
7. }
1. public class HomeController : BaseController
2. {
3. //
4. // GET: /Home/
5. public ActionResult Index()
6. {
7. string FullName = User.FirstName + " " + User.LastName;
8. return View();
9. }
10. }
Base View Page for accessing Current User
Create a base class for all your views for accessing your User data in your all views as shown below:
1. public abstract class BaseViewPage : WebViewPage
2. {
3. public virtual new CustomPrincipal User
4. {
5. get { return base.User as CustomPrincipal; }
6. }
7. }
8. public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
9. {
10. public virtual new CustomPrincipal User
11. {
12. get { return base.User as CustomPrincipal; }
13. }
14. }
Register this class with in the \Views\Web.config as base class for all your views as given below:
<system.web.webPages.razor>
<!--Other code has been removed for clarity--> <pages pageBaseType="Security.DAL.Security.BaseViewPage"> <namespaces> <!--Other code has been removed for clarity--> </namespaces> </pages> </system.web.webPages.razor>
Now you can access the authenticated user information on all your view in easy and simple way as shown below in Admin View:
1. @{
2. ViewBag.Title = "Index";
3. Layout = "~/Views/Shared/_AdminLayout.cshtml";
4. }
5. <h4>Welcome : @User.FirstName</h4>
6. <h1>Admin DashBoard</h1>
Login View
@model Security.Models.LoginViewModel @{ ViewBag.Title = "Index";} @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>User Login</h4> <hr /> @Html.ValidationSummary(true) <div class="form-group"> @Html.LabelFor(model => model.Username, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Username) @Html.ValidationMessageFor(model => model.Username) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Password) @Html.ValidationMessageFor(model => model.Password) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.RememberMe, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.RememberMe) @Html.ValidationMessageFor(model => model.RememberMe) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Login" class="btn btn-default" /> </div> </div> </div>}Applying CustomAuthorize attributeTo make secure your admin or user pages, decorate your Admin and User controllers with CustomAuthorize attribute as defined above and specify the uses or roles to access admin and user pages.
1. [CustomAuthorize(Roles= "Admin")]
2. // [CustomAuthorize(Users = "1")]
3. public class AdminController : BaseController
4. {
5. //
6. // GET: /Admin/
7. public ActionResult Index()
8. {
9. return View();
10. }
11. }
1.
2. [CustomAuthorize(Roles= "User")]
3. // [CustomAuthorize(Users = "1,2")]
4. public class UserController : BaseController
5. {
6. //
7. // GET: /User/
8. public ActionResult Index()
9. {
10. return View();
11. }
12. }
You can also specify the Roles and Users with in your web.config as a key to avoid hard code values for Users and Roles at the controller level.
- <add key="RolesConfigKey" value="Admin"/>
- <add key="UsersConfigKey" value="2,3"/>
Use one of these keys within the CustomAuthorize attribute as shown below:
1. //[CustomAuthorize(RolesConfigKey = "RolesConfigKey")]
2. [CustomAuthorize(UsersConfigKey = "UsersConfigKey")]
3.
4. public class AdminController : BaseController
5. {
6. //
7. // GET: /Admin/
8. public ActionResult Index()
9. {
10. return View();
11. }
12. }
1. [CustomAuthorize(RolesConfigKey = "RolesConfigKey")]
2. // [CustomAuthorize(UsersConfigKey = "UsersConfigKey")]
3. public class UserController : BaseController
4. {
5. //
6. // GET: /User/
7. public ActionResult Index()
8. {
9. return View();
10. }
11. }
Test your application
When you will run your application and will login into the application using user1, you will be redirected to User dashboard as shown below:
When user will try to access unauthorized pages such as Admin dashboard using URL: http://localhost:11681/Admin , he will get the custom error page as shown below: