Saturday, August 10, 2019

Part 3 - How to implement custom Forms Authentication in ASP.NET MVC4 application

Step-1 : Create 2 tables.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

Table Name : Roles



Table Name : UserRoles


Step-2: update Entity Data Model.

Go to Solution Explorer > Open Model (created in the part 1) > Right click on empty area (inside model) > Update model from Database > Add Tables > Finish.

Step-3 : Add a class for extends RoleProvider class.

Go to solution explorer > Right click on the project name > Add > Class > Enter class name > Add
Here we will extend RoleProvider class.

Step-4 : Override two method "GetRolesForUser" and "IsUserInRole" of RoleProvider class.

Complete Code 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Caching;
  6. using System.Web.Security;
  7.  
  8. namespace MvcAuthentication
  9. {
  10. public class MyRoleProvider : RoleProvider
  11. {
  12. private int _cacheTimeoutInMinute = 20;
  13. public override void AddUsersToRoles(string[] usernames, string[] roleNames)
  14. {
  15. throw new NotImplementedException();
  16. }
  17.  
  18. public override string ApplicationName
  19. {
  20. get
  21. {
  22. throw new NotImplementedException();
  23. }
  24. set
  25. {
  26. throw new NotImplementedException();
  27. }
  28. }
  29.  
  30. public override void CreateRole(string roleName)
  31. {
  32. throw new NotImplementedException();
  33. }
  34.  
  35. public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
  36. {
  37. throw new NotImplementedException();
  38. }
  39.  
  40. public override string[] FindUsersInRole(string roleName, string usernameToMatch)
  41. {
  42. throw new NotImplementedException();
  43. }
  44.  
  45. public override string[] GetAllRoles()
  46. {
  47. throw new NotImplementedException();
  48. }
  49.  
  50. public override string[] GetRolesForUser(string username)
  51. {
  52. if (!HttpContext.Current.User.Identity.IsAuthenticated)
  53. {
  54. return null;
  55. }
  56.  
  57. //check cache
  58. var cacheKey = string.Format("{0}_role", username);
  59. if (HttpRuntime.Cache[cacheKey] != null)
  60. {
  61. return (string[])HttpRuntime.Cache[cacheKey];
  62. }
  63. string[] roles = new string[]{};
  64. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  65. {
  66. roles = (from a in dc.Roles
  67. join b in dc.UserRoles on a.RoleID equals b.RoleID
  68. join c in dc.Users on b.UserID equals c.UserID
  69. where c.Username.Equals(username)
  70. select a.ROleName).ToArray<string>();
  71. if (roles.Count() > 0)
  72. {
  73. HttpRuntime.Cache.Insert(cacheKey, roles, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinute), Cache.NoSlidingExpiration);
  74.  
  75. }
  76. }
  77. return roles;
  78. }
  79.  
  80. public override string[] GetUsersInRole(string roleName)
  81. {
  82. throw new NotImplementedException();
  83. }
  84.  
  85. public override bool IsUserInRole(string username, string roleName)
  86. {
  87. var userRoles = GetRolesForUser(username);
  88. return userRoles.Contains(roleName);
  89. }
  90.  
  91. public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
  92. {
  93. throw new NotImplementedException();
  94. }
  95.  
  96. public override bool RoleExists(string roleName)
  97. {
  98. throw new NotImplementedException();
  99. }
  100. }
  101. }

Step-5: Edit web.config for Enable our custom role provider.

In this example, I have written the following configuration in the web.config file for Enable our custom role provider
  1. <roleManager defaultProvider="MyRoleProvider" enabled="true">
  2. <providers>
  3. <add name="MyRoleProvider" type="MvcAuthentication.MyRoleProvider, MvcAuthentication"/>
  4. </providers>
  5. </roleManager>

Step-6: Add new action into your controller (here in HomeController) for "Admin" role user

Here I have used "AdminIndex" Action. Please write this following code
  1. [Authorize(Roles="Admin")]
  2. public ActionResult AdminIndex()
  3. {
  4. return View();
  5. }

Step-7: Add view for the Action (here in "AdminIndex") & design.

Right Click on Action Method (here right click on "AdminIndex" action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
  1. @{
  2. ViewBag.Title = "AdminIndex";
  3. }
  4.  
  5. <h2>Admin Index</h2>
  6. <div>Welcome @(Request.IsAuthenticated? HttpContext.Current.User.Identity.Name : "") (Admin)</div>

Step-8: Add new action into your controller (here in HomeController) for "User" role user

Here I have used "UserIndex" Action. Please write this following code
  1. [Authorize(Roles="User")]
  2. public ActionResult UserIndex()
  3. {
  4. return View();
  5. }

Step-9: Add view for the Action (here in "UserIndex") & design.

Right Click on Action Method (here right click on "UserIndex" action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
  1. @{
  2. ViewBag.Title = "UserIndex";
  3. }
  4.  
  5. <h2>User Index</h2>
  6. <div>Welcome @(Request.IsAuthenticated? HttpContext.Current.User.Identity.Name : "") (User) </div>
  7.  
  8.  

Step-10: Run Application.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...