Saturday, August 10, 2019

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

Step-1 : Add a class for extends MembershipProvider class. Go to solution explorer > Right click on the project name > Add > Class > Enter class name > Add
Here we will extend MembershipProvider class.
for now I have just implemented only the ValidateUser method because this is the only method needed to validate the user credentials. we will see the other features of the membership provider later.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Security;
  6.  
  7. namespace MvcAuthentication
  8. {
  9. public class MyMembershipProvider : MembershipProvider
  10. {
  11. public override string ApplicationName
  12. {
  13. get
  14. {
  15. throw new NotImplementedException();
  16. }
  17. set
  18. {
  19. throw new NotImplementedException();
  20. }
  21. }
  22.  
  23. public override bool ChangePassword(string username, string oldPassword, string newPassword)
  24. {
  25. throw new NotImplementedException();
  26. }
  27.  
  28. public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
  29. {
  30. throw new NotImplementedException();
  31. }
  32.  
  33. public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
  34. {
  35. throw new NotImplementedException();
  36. }
  37.  
  38. public override bool DeleteUser(string username, bool deleteAllRelatedData)
  39. {
  40. throw new NotImplementedException();
  41. }
  42.  
  43. public override bool EnablePasswordReset
  44. {
  45. get { throw new NotImplementedException(); }
  46. }
  47.  
  48. public override bool EnablePasswordRetrieval
  49. {
  50. get { throw new NotImplementedException(); }
  51. }
  52.  
  53. public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
  54. {
  55. throw new NotImplementedException();
  56. }
  57.  
  58. public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
  59. {
  60. throw new NotImplementedException();
  61. }
  62.  
  63. public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
  64. {
  65. throw new NotImplementedException();
  66. }
  67.  
  68. public override int GetNumberOfUsersOnline()
  69. {
  70. throw new NotImplementedException();
  71. }
  72.  
  73. public override string GetPassword(string username, string answer)
  74. {
  75. throw new NotImplementedException();
  76. }
  77.  
  78. public override MembershipUser GetUser(string username, bool userIsOnline)
  79. {
  80. throw new NotImplementedException();
  81. }
  82.  
  83. public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
  84. {
  85. throw new NotImplementedException();
  86. }
  87.  
  88. public override string GetUserNameByEmail(string email)
  89. {
  90. throw new NotImplementedException();
  91. }
  92.  
  93. public override int MaxInvalidPasswordAttempts
  94. {
  95. get { throw new NotImplementedException(); }
  96. }
  97.  
  98. public override int MinRequiredNonAlphanumericCharacters
  99. {
  100. get { throw new NotImplementedException(); }
  101. }
  102.  
  103. public override int MinRequiredPasswordLength
  104. {
  105. get { throw new NotImplementedException(); }
  106. }
  107.  
  108. public override int PasswordAttemptWindow
  109. {
  110. get { throw new NotImplementedException(); }
  111. }
  112.  
  113. public override MembershipPasswordFormat PasswordFormat
  114. {
  115. get { throw new NotImplementedException(); }
  116. }
  117.  
  118. public override string PasswordStrengthRegularExpression
  119. {
  120. get { throw new NotImplementedException(); }
  121. }
  122.  
  123. public override bool RequiresQuestionAndAnswer
  124. {
  125. get { throw new NotImplementedException(); }
  126. }
  127.  
  128. public override bool RequiresUniqueEmail
  129. {
  130. get { throw new NotImplementedException(); }
  131. }
  132.  
  133. public override string ResetPassword(string username, string answer)
  134. {
  135. throw new NotImplementedException();
  136. }
  137.  
  138. public override bool UnlockUser(string userName)
  139. {
  140. throw new NotImplementedException();
  141. }
  142.  
  143. public override void UpdateUser(MembershipUser user)
  144. {
  145. throw new NotImplementedException();
  146. }
  147.  
  148.  
  149. // Here In this example we will use only ValidateUser method, we will see remaining later like create user,
  150. //update user change password and more
  151.  
  152. public override bool ValidateUser(string username, string password)
  153. {
  154. //Will write code for validate user from our own database
  155. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  156. {
  157. var user = dc.Users.Where(a => a.Username.Equals(username) && a.Password.Equals(password)).FirstOrDefault();
  158. if (user != null)
  159. {
  160. return true;
  161. }
  162. }
  163. return false;
  164. }
  165. }
  166. }

Step-2: Update Login POST Action code of MyAccountController (created in the part 1) .

Here I have replaced the existing code for verify user (used in part 1) for use our own custom membership provider's ValidateUser method
  1. [HttpPost]
  2. [ValidateAntiForgeryToken]
  3. public ActionResult Login(Login l, string ReturnUrl = "")
  4. {
  5.  
  6. // Here we will replace our existing code (what I have used in the previous part) used for clear understanding
  7. #region Existing Code
  8. //using (MyDatabaseEntities dc = new MyDatabaseEntities())
  9. //{
  10. // var user = dc.Users.Where(a => a.Username.Equals(l.Username) && a.Password.Equals(l.Password)).FirstOrDefault();
  11. // if (user != null)
  12. // {
  13. // FormsAuthentication.SetAuthCookie(user.Username, l.RememberMe);
  14. // if (Url.IsLocalUrl(ReturnUrl))
  15. // {
  16. // return Redirect(ReturnUrl);
  17. // }
  18. // else
  19. // {
  20. // return RedirectToAction("MyProfile", "Home");
  21. // }
  22. // }
  23. //}
  24. #endregion
  25. //Here I am going to use Membership provider to validate user
  26. if (ModelState.IsValid)
  27. {
  28. var isValidUser = Membership.ValidateUser(l.Username, l.Password);
  29. if (isValidUser)
  30. {
  31. FormsAuthentication.SetAuthCookie(l.Username, l.RememberMe);
  32. if (Url.IsLocalUrl(ReturnUrl))
  33. {
  34. return Redirect(ReturnUrl);
  35. }
  36. else
  37. {
  38. return RedirectToAction("Index", "Home");
  39. }
  40. }
  41. }
  42. ModelState.Remove("Password");
  43. return View();
  44. }

Step-3: Edit web.config for Enable our custom membership provider.

In this example, I have written the following configuration in the web.config file for Enable our custom membership provider
  1. <membership defaultProvider="MyMembershipProvider">
  2. <providers>
  3. <add name="MyMembershipProvider" type="MvcAuthentication.MyMembershipProvider, MvcAuthentication"/>
  4. <!--<add name="ClassName" type="NamespaceName.ClassName, assemble (dll) name"/>-->
  5. </providers>
  6. </membership>

Step-4: 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 { ...