Step 1: Create Table.

query

  1. CREATE TABLE [dbo].[Roles](
  2. [RoleID] [int] IDENTITY(1,1) NOT NULL,
  3. [ROleName] [varchar](50) NOT NULL,
  4. PRIMARY KEY CLUSTERED
  5. (
  6. [RoleID] ASC
  7. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  8. ) ON [PRIMARY]
  9. GO
  10. SET ANSI_PADDING OFF
  11. GO
  12. /****** Object: Table [dbo].[UserRoles] Script Date: 7/4/2015 5:55:16 PM ******/
  13. SET ANSI_NULLS ON
  14. GO
  15. SET QUOTED_IDENTIFIER ON
  16. GO
  17. CREATE TABLE [dbo].[UserRoles](
  18. [UserRolesID] [int] IDENTITY(1,1) NOT NULL,
  19. [RoleID] [int] NOT NULL,
  20. [UserID] [int] NOT NULL,
  21. PRIMARY KEY CLUSTERED
  22. (
  23. [UserRolesID] ASC
  24. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  25. ) ON [PRIMARY]
  26. GO
  27. /****** Object: Table [dbo].[Users] Script Date: 7/4/2015 5:55:16 PM ******/
  28. SET ANSI_NULLS ON
  29. GO
  30. SET QUOTED_IDENTIFIER ON
  31. GO
  32. SET ANSI_PADDING ON
  33. GO
  34. CREATE TABLE [dbo].[Users](
  35. [UserID] [int] IDENTITY(1,1) NOT NULL,
  36. [Username] [varchar](50) NOT NULL,
  37. [Password] [varchar](50) NOT NULL,
  38. [FirstName] [varchar](50) NOT NULL,
  39. [LastName] [varchar](50) NULL,
  40. [EmailID] [varchar](200) NULL,
  41. PRIMARY KEY CLUSTERED
  42. (
  43. [UserID] ASC
  44. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  45. ) ON [PRIMARY]
  46. GO
  47. SET ANSI_PADDING OFF
  48. GO
  49. SET IDENTITY_INSERT [dbo].[Roles] ON
  50. GO
  51. INSERT [dbo].[Roles] ([RoleID], [ROleName]) VALUES (1, N'Admin')
  52. GO
  53. INSERT [dbo].[Roles] ([RoleID], [ROleName]) VALUES (2, N'User')
  54. GO
  55. SET IDENTITY_INSERT [dbo].[Roles] OFF
  56. GO
  57. SET IDENTITY_INSERT [dbo].[UserRoles] ON
  58. GO
  59. INSERT [dbo].[UserRoles] ([UserRolesID], [RoleID], [UserID]) VALUES (1, 1, 1)
  60. GO
  61. INSERT [dbo].[UserRoles] ([UserRolesID], [RoleID], [UserID]) VALUES (2, 2, 2)
  62. GO
  63. SET IDENTITY_INSERT [dbo].[UserRoles] OFF
  64. GO
  65. SET IDENTITY_INSERT [dbo].[Users] ON
  66. GO
  67. INSERT [dbo].[Users] ([UserID], [Username], [Password], [FirstName], [LastName], [EmailID]) VALUES (1, N'knk', N'knk', N'sample', N'sample1', N'[email protected]')
  68. GO
  69. INSERT [dbo].[Users] ([UserID], [Username], [Password], [FirstName], [LastName], [EmailID]) VALUES (2, N'kumar', N'kumar', N'run', N'ran', N'[email protected]')
  70. GO
  71. SET IDENTITY_INSERT [dbo].[Users] OFF
  72. GO

Step 2: Create a project.

Go to File, then New and click Project. Select ASP.NET MVC 4 Web Application and enter the project name, then click OK, select Empty, select View Engine Razor and press OK.

Step 3: Add model

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Web;
  6. namespace MvcApplication2.Models {
  7. public class login {
  8. [Required(ErrorMessage = "Username required.", AllowEmptyStrings = false)]
  9. public string Username {
  10. get;
  11. set;
  12. }
  13. [Required(ErrorMessage = "Password required.", AllowEmptyStrings = false)]
  14. [DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
  15. public string Password {
  16. get;
  17. set;
  18. }
  19. public bool RememberMe {
  20. get;
  21. set;
  22. }
  23. }
  24. }

Step 4: Add Home Controller.

add controller

Home Contrtoller.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace MvcAuthentication.Controllers {
  7. public class HomeController: Controller {
  8. [AllowAnonymous] //This is for Un-Authorize User
  9. public ActionResult Index() {
  10. return View();
  11. }
  12. [Authorize] // This is for Authorize user
  13. public ActionResult MyProfile() {
  14. return View();
  15. }
  16. [Authorize(Roles = "Admin")]
  17. public ActionResult AdminIndex() {
  18. return View();
  19. }
  20. [Authorize(Roles = "User")]
  21. public ActionResult UserIndex() {
  22. return View();
  23. }
  24. }
  25. }

Step 5: Add view.

add

Index.cshtml;

  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. <h2>Index</h2>
  5. <h3>Welcome Guest - This is for all the anonymous user</h3>
  6. Myprofile.cshtml
  7. @{
  8. ViewBag.Title = "MyProfile";
  9. }
  10. <h2>My Profile</h2>
  11. <h3>Welcome @(Request.IsAuthenticated ? HttpContext.Current.User.Identity.Name : "Guest") - This is for Authorized user </h3>

Userindex.cshtml

  1. @{
  2. ViewBag.Title = "UserIndex";
  3. }
  4. <h2>User Index</h2>
  5. <div>Welcome @(Request.IsAuthenticated? HttpContext.Current.User.Identity.Name : "") (User) </div>

Admin.cshtml

  1. @{
  2. ViewBag.Title = "AdminIndex";
  3. }
  4. <h2>Admin Index</h2>
  5. <div>Welcome @(Request.IsAuthenticated? HttpContext.Current.User.Identity.Name : "") (Admin)</div>

Step 6: Add Myaccount Controller:

MyAccountController.cs

  1. using MvcAuthentication.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. using System.Web.Security;
  8. namespace MvcAuthentication.Controllers {
  9. public class MyAccountController: Controller {
  10. public ActionResult Login() {
  11. return View();
  12. }
  13. [HttpPost]
  14. [ValidateAntiForgeryToken]
  15. public ActionResult Login(Login l, string ReturnUrl = "") {
  16. //Here I am going to use Membership provider to validate user
  17. if (ModelState.IsValid) {
  18. var isValidUser = Membership.ValidateUser(l.Username, l.Password);
  19. if (isValidUser) {
  20. FormsAuthentication.SetAuthCookie(l.Username, l.RememberMe);
  21. if (Url.IsLocalUrl(ReturnUrl)) {
  22. return Redirect(ReturnUrl);
  23. } else {
  24. return RedirectToAction("Index", "Home");
  25. }
  26. }
  27. }
  28. ModelState.Remove("Password");
  29. return View();
  30. }
  31. [Authorize]
  32. public ActionResult Logout() {
  33. FormsAuthentication.SignOut();
  34. return RedirectToAction("Index", "Home");
  35. }
  36. }
  37. }

Step 7: Add view Myaccount.

Login.cshtml;

  1. @model MvcAuthentication.Models.Login
  2. @{
  3. ViewBag.Title = "Login";
  4. }
  5. <h2>Login</h2>
  6. @using (Html.BeginForm()) {
  7. @Html.ValidationSummary(true)
  8. @Html.AntiForgeryToken()
  9. <fieldset>
  10. <legend>Login</legend>
  11. <div class="editor-label">
  12. @Html.LabelFor(model => model.Username)
  13. </div>
  14. <div class="editor-field">
  15. @Html.EditorFor(model => model.Username)
  16. @Html.ValidationMessageFor(model => model.Username)
  17. </div>
  18. <div class="editor-label">
  19. @Html.LabelFor(model => model.Password)
  20. </div>
  21. <div class="editor-field">
  22. @Html.EditorFor(model => model.Password)
  23. @Html.ValidationMessageFor(model => model.Password)
  24. </div>
  25. <div class="editor-label">
  26. @Html.LabelFor(model => model.RememberMe)
  27. </div>
  28. <div class="editor-field">
  29. @Html.EditorFor(model => model.RememberMe)
  30. @Html.ValidationMessageFor(model => model.RememberMe)
  31. </div>
  32. <p>
  33. <input type="submit" value="Create" />
  34. </p>
  35. </fieldset>
  36. }
  37. <div>
  38. @Html.ActionLink("Back to List", "Index")
  39. </div>
  40. @section Scripts {
  41. @Scripts.Render("~/bundles/jqueryval")
  42. }

Step 8: Add Entity Data Model.

table

Step 9: Add two cs Files.

MyRoleProvider.cs

  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. namespace MvcAuthentication {
  8. public class MyRoleProvider: RoleProvider {
  9. private int _cacheTimeoutInMinute = 20;
  10. public override void AddUsersToRoles(string[] usernames, string[] roleNames) {
  11. throw new NotImplementedException();
  12. }
  13. public override string ApplicationName {
  14. get {
  15. throw new NotImplementedException();
  16. }
  17. set {
  18. throw new NotImplementedException();
  19. }
  20. }
  21. public override void CreateRole(string roleName) {
  22. throw new NotImplementedException();
  23. }
  24. public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) {
  25. throw new NotImplementedException();
  26. }
  27. public override string[] FindUsersInRole(string roleName, string usernameToMatch) {
  28. throw new NotImplementedException();
  29. }
  30. public override string[] GetAllRoles() {
  31. throw new NotImplementedException();
  32. }
  33. public override string[] GetRolesForUser(string username) {
  34. if (!HttpContext.Current.User.Identity.IsAuthenticated) {
  35. return null;
  36. }
  37. //check cache
  38. var cacheKey = string.Format("{0}_role", username);
  39. if (HttpRuntime.Cache[cacheKey] != null) {
  40. return (string[]) HttpRuntime.Cache[cacheKey];
  41. }
  42. string[] roles = new string[] {};
  43. using(RBACEntities dc = new RBACEntities()) {
  44. roles = (from a in dc.Roles
  45. join b in dc.UserRoles on a.RoleID equals b.RoleID
  46. join c in dc.Users on b.UserID equals c.UserID
  47. where c.Username.Equals(username)
  48. select a.ROleName).ToArray < string > ();
  49. if (roles.Count() > 0) {
  50. HttpRuntime.Cache.Insert(cacheKey, roles, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinute), Cache.NoSlidingExpiration);
  51. }
  52. }
  53. return roles;
  54. }
  55. public override string[] GetUsersInRole(string roleName) {
  56. throw new NotImplementedException();
  57. }
  58. public override bool IsUserInRole(string username, string roleName) {
  59. var userRoles = GetRolesForUser(username);
  60. return userRoles.Contains(roleName);
  61. }
  62. public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) {
  63. throw new NotImplementedException();
  64. }
  65. public override bool RoleExists(string roleName) {
  66. throw new NotImplementedException();
  67. }
  68. }
  69. }

MyMembershipProvider.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Security;
  6. namespace MvcAuthentication {
  7. public class MyMembershipProvider: MembershipProvider {
  8. public override string ApplicationName {
  9. get {
  10. throw new NotImplementedException();
  11. }
  12. set {
  13. throw new NotImplementedException();
  14. }
  15. }
  16. public override bool ChangePassword(string username, string oldPassword, string newPassword) {
  17. throw new NotImplementedException();
  18. }
  19. public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) {
  20. throw new NotImplementedException();
  21. }
  22. public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) {
  23. throw new NotImplementedException();
  24. }
  25. public override bool DeleteUser(string username, bool deleteAllRelatedData) {
  26. throw new NotImplementedException();
  27. }
  28. public override bool EnablePasswordReset {
  29. get {
  30. throw new NotImplementedException();
  31. }
  32. }
  33. public override bool EnablePasswordRetrieval {
  34. get {
  35. throw new NotImplementedException();
  36. }
  37. }
  38. public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) {
  39. throw new NotImplementedException();
  40. }
  41. public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) {
  42. throw new NotImplementedException();
  43. }
  44. public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) {
  45. throw new NotImplementedException();
  46. }
  47. public override int GetNumberOfUsersOnline() {
  48. throw new NotImplementedException();
  49. }
  50. public override string GetPassword(string username, string answer) {
  51. throw new NotImplementedException();
  52. }
  53. public override MembershipUser GetUser(string username, bool userIsOnline) {
  54. throw new NotImplementedException();
  55. }
  56. public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) {
  57. throw new NotImplementedException();
  58. }
  59. public override string GetUserNameByEmail(string email) {
  60. throw new NotImplementedException();
  61. }
  62. public override int MaxInvalidPasswordAttempts {
  63. get {
  64. throw new NotImplementedException();
  65. }
  66. }
  67. public override int MinRequiredNonAlphanumericCharacters {
  68. get {
  69. throw new NotImplementedException();
  70. }
  71. }
  72. public override int MinRequiredPasswordLength {
  73. get {
  74. throw new NotImplementedException();
  75. }
  76. }
  77. public override int PasswordAttemptWindow {
  78. get {
  79. throw new NotImplementedException();
  80. }
  81. }
  82. public override MembershipPasswordFormat PasswordFormat {
  83. get {
  84. throw new NotImplementedException();
  85. }
  86. }
  87. public override string PasswordStrengthRegularExpression {
  88. get {
  89. throw new NotImplementedException();
  90. }
  91. }
  92. public override bool RequiresQuestionAndAnswer {
  93. get {
  94. throw new NotImplementedException();
  95. }
  96. }
  97. public override bool RequiresUniqueEmail {
  98. get {
  99. throw new NotImplementedException();
  100. }
  101. }
  102. public override string ResetPassword(string username, string answer) {
  103. throw new NotImplementedException();
  104. }
  105. public override bool UnlockUser(string userName) {
  106. throw new NotImplementedException();
  107. }
  108. public override void UpdateUser(MembershipUser user) {
  109. throw new NotImplementedException();
  110. }
  111. // Here In this example we will use only ValidateUser method, we will see remaining later like create user,
  112. //update user change password and more
  113. public override bool ValidateUser(string username, string password) {
  114. //Will write code for validate user from our own database
  115. using(RBACEntities dc = new RBACEntities()) {
  116. var user = dc.Users.Where(a = > a.Username.Equals(username) && a.Password.Equals(password)).FirstOrDefault();
  117. if (user != null) {
  118. return true;
  119. }
  120. }
  121. return false;
  122. }
  123. }
  124. }

Step 10: Web Config File.

code