Step 1: Create Table.
- CREATE TABLE [dbo].[Roles](
- [RoleID] [int] IDENTITY(1,1) NOT NULL,
- [ROleName] [varchar](50) NOT NULL,
- PRIMARY KEY CLUSTERED
- (
- [RoleID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- SET ANSI_PADDING OFF
- GO
- /****** Object: Table [dbo].[UserRoles] Script Date: 7/4/2015 5:55:16 PM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE TABLE [dbo].[UserRoles](
- [UserRolesID] [int] IDENTITY(1,1) NOT NULL,
- [RoleID] [int] NOT NULL,
- [UserID] [int] NOT NULL,
- PRIMARY KEY CLUSTERED
- (
- [UserRolesID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- /****** Object: Table [dbo].[Users] Script Date: 7/4/2015 5:55:16 PM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- SET ANSI_PADDING ON
- GO
- CREATE TABLE [dbo].[Users](
- [UserID] [int] IDENTITY(1,1) NOT NULL,
- [Username] [varchar](50) NOT NULL,
- [Password] [varchar](50) NOT NULL,
- [FirstName] [varchar](50) NOT NULL,
- [LastName] [varchar](50) NULL,
- [EmailID] [varchar](200) NULL,
- PRIMARY KEY CLUSTERED
- (
- [UserID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- SET ANSI_PADDING OFF
- GO
- SET IDENTITY_INSERT [dbo].[Roles] ON
- GO
- INSERT [dbo].[Roles] ([RoleID], [ROleName]) VALUES (1, N'Admin')
- GO
- INSERT [dbo].[Roles] ([RoleID], [ROleName]) VALUES (2, N'User')
- GO
- SET IDENTITY_INSERT [dbo].[Roles] OFF
- GO
- SET IDENTITY_INSERT [dbo].[UserRoles] ON
- GO
- INSERT [dbo].[UserRoles] ([UserRolesID], [RoleID], [UserID]) VALUES (1, 1, 1)
- GO
- INSERT [dbo].[UserRoles] ([UserRolesID], [RoleID], [UserID]) VALUES (2, 2, 2)
- GO
- SET IDENTITY_INSERT [dbo].[UserRoles] OFF
- GO
- SET IDENTITY_INSERT [dbo].[Users] ON
- GO
- INSERT [dbo].[Users] ([UserID], [Username], [Password], [FirstName], [LastName], [EmailID]) VALUES (1, N'knk', N'knk', N'sample', N'sample1', N'[email protected]')
- GO
- INSERT [dbo].[Users] ([UserID], [Username], [Password], [FirstName], [LastName], [EmailID]) VALUES (2, N'kumar', N'kumar', N'run', N'ran', N'[email protected]')
- GO
- SET IDENTITY_INSERT [dbo].[Users] OFF
- 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
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
- namespace MvcApplication2.Models {
- public class login {
- [Required(ErrorMessage = "Username required.", AllowEmptyStrings = false)]
- public string Username {
- get;
- set;
- }
- [Required(ErrorMessage = "Password required.", AllowEmptyStrings = false)]
- [DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
- public string Password {
- get;
- set;
- }
- public bool RememberMe {
- get;
- set;
- }
- }
- }
Step 4: Add Home Controller.
Home Contrtoller.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcAuthentication.Controllers {
- public class HomeController: Controller {
- [AllowAnonymous]
- public ActionResult Index() {
- return View();
- }
-
- [Authorize]
- public ActionResult MyProfile() {
- return View();
- }
-
- [Authorize(Roles = "Admin")]
- public ActionResult AdminIndex() {
- return View();
- }
-
- [Authorize(Roles = "User")]
- public ActionResult UserIndex() {
- return View();
- }
-
- }
- }
Step 5: Add view.
Index.cshtml;
- @{
- ViewBag.Title = "Index";
- }
- <h2>Index</h2>
- <h3>Welcome Guest - This is for all the anonymous user</h3>
- Myprofile.cshtml
- @{
- ViewBag.Title = "MyProfile";
- }
- <h2>My Profile</h2>
- <h3>Welcome @(Request.IsAuthenticated ? HttpContext.Current.User.Identity.Name : "Guest") - This is for Authorized user </h3>
Userindex.cshtml
- @{
- ViewBag.Title = "UserIndex";
- }
- <h2>User Index</h2>
- <div>Welcome @(Request.IsAuthenticated? HttpContext.Current.User.Identity.Name : "") (User) </div>
Admin.cshtml
- @{
- ViewBag.Title = "AdminIndex";
- }
- <h2>Admin Index</h2>
- <div>Welcome @(Request.IsAuthenticated? HttpContext.Current.User.Identity.Name : "") (Admin)</div>
Step 6: Add Myaccount Controller:
MyAccountController.cs
- using MvcAuthentication.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Security;
-
- namespace MvcAuthentication.Controllers {
- public class MyAccountController: Controller {
- public ActionResult Login() {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Login(Login l, string ReturnUrl = "") {
-
-
-
- if (ModelState.IsValid) {
- var isValidUser = Membership.ValidateUser(l.Username, l.Password);
- if (isValidUser) {
- FormsAuthentication.SetAuthCookie(l.Username, l.RememberMe);
- if (Url.IsLocalUrl(ReturnUrl)) {
- return Redirect(ReturnUrl);
- } else {
- return RedirectToAction("Index", "Home");
- }
- }
- }
-
-
- ModelState.Remove("Password");
- return View();
- }
-
- [Authorize]
- public ActionResult Logout() {
- FormsAuthentication.SignOut();
- return RedirectToAction("Index", "Home");
- }
- }
- }
Step 7: Add view Myaccount.
Login.cshtml;
- @model MvcAuthentication.Models.Login
-
- @{
- ViewBag.Title = "Login";
- }
-
- <h2>Login</h2>
-
- @using (Html.BeginForm()) {
- @Html.ValidationSummary(true)
- @Html.AntiForgeryToken()
- <fieldset>
- <legend>Login</legend>
- <div class="editor-label">
- @Html.LabelFor(model => model.Username)
- </div>
- <div class="editor-field">
- @Html.EditorFor(model => model.Username)
- @Html.ValidationMessageFor(model => model.Username)
- </div>
- <div class="editor-label">
- @Html.LabelFor(model => model.Password)
- </div>
- <div class="editor-field">
- @Html.EditorFor(model => model.Password)
- @Html.ValidationMessageFor(model => model.Password)
- </div>
- <div class="editor-label">
- @Html.LabelFor(model => model.RememberMe)
- </div>
- <div class="editor-field">
- @Html.EditorFor(model => model.RememberMe)
- @Html.ValidationMessageFor(model => model.RememberMe)
- </div>
- <p>
- <input type="submit" value="Create" />
- </p>
- </fieldset>
-
- }
-
-
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
-
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- }
Step 8: Add Entity Data Model.
Step 9: Add two cs Files.
MyRoleProvider.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Caching;
- using System.Web.Security;
-
- namespace MvcAuthentication {
- public class MyRoleProvider: RoleProvider {
- private int _cacheTimeoutInMinute = 20;
- public override void AddUsersToRoles(string[] usernames, string[] roleNames) {
- throw new NotImplementedException();
- }
-
- public override string ApplicationName {
- get {
- throw new NotImplementedException();
- }
- set {
- throw new NotImplementedException();
- }
- }
-
- public override void CreateRole(string roleName) {
- throw new NotImplementedException();
- }
-
- public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) {
- throw new NotImplementedException();
- }
-
- public override string[] FindUsersInRole(string roleName, string usernameToMatch) {
- throw new NotImplementedException();
- }
-
- public override string[] GetAllRoles() {
- throw new NotImplementedException();
- }
-
- public override string[] GetRolesForUser(string username) {
- if (!HttpContext.Current.User.Identity.IsAuthenticated) {
- return null;
- }
-
-
- var cacheKey = string.Format("{0}_role", username);
- if (HttpRuntime.Cache[cacheKey] != null) {
- return (string[]) HttpRuntime.Cache[cacheKey];
- }
- string[] roles = new string[] {};
- using(RBACEntities dc = new RBACEntities()) {
- roles = (from a in dc.Roles
- join b in dc.UserRoles on a.RoleID equals b.RoleID
- join c in dc.Users on b.UserID equals c.UserID
- where c.Username.Equals(username)
- select a.ROleName).ToArray < string > ();
- if (roles.Count() > 0) {
- HttpRuntime.Cache.Insert(cacheKey, roles, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinute), Cache.NoSlidingExpiration);
-
- }
- }
- return roles;
- }
-
- public override string[] GetUsersInRole(string roleName) {
- throw new NotImplementedException();
- }
-
- public override bool IsUserInRole(string username, string roleName) {
- var userRoles = GetRolesForUser(username);
- return userRoles.Contains(roleName);
- }
-
- public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) {
- throw new NotImplementedException();
- }
-
- public override bool RoleExists(string roleName) {
- throw new NotImplementedException();
- }
- }
- }
MyMembershipProvider.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Security;
-
- namespace MvcAuthentication {
- public class MyMembershipProvider: MembershipProvider {
- public override string ApplicationName {
- get {
- throw new NotImplementedException();
- }
- set {
- throw new NotImplementedException();
- }
- }
-
- public override bool ChangePassword(string username, string oldPassword, string newPassword) {
- throw new NotImplementedException();
- }
-
- public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) {
- throw new NotImplementedException();
- }
-
- public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) {
- throw new NotImplementedException();
- }
-
- public override bool DeleteUser(string username, bool deleteAllRelatedData) {
- throw new NotImplementedException();
- }
-
- public override bool EnablePasswordReset {
- get {
- throw new NotImplementedException();
- }
- }
-
- public override bool EnablePasswordRetrieval {
- get {
- throw new NotImplementedException();
- }
- }
-
- public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) {
- throw new NotImplementedException();
- }
-
- public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) {
- throw new NotImplementedException();
- }
-
- public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) {
- throw new NotImplementedException();
- }
-
- public override int GetNumberOfUsersOnline() {
- throw new NotImplementedException();
- }
-
- public override string GetPassword(string username, string answer) {
- throw new NotImplementedException();
- }
-
- public override MembershipUser GetUser(string username, bool userIsOnline) {
- throw new NotImplementedException();
- }
-
- public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) {
- throw new NotImplementedException();
- }
-
- public override string GetUserNameByEmail(string email) {
- throw new NotImplementedException();
- }
-
- public override int MaxInvalidPasswordAttempts {
- get {
- throw new NotImplementedException();
- }
- }
-
- public override int MinRequiredNonAlphanumericCharacters {
- get {
- throw new NotImplementedException();
- }
- }
-
- public override int MinRequiredPasswordLength {
- get {
- throw new NotImplementedException();
- }
- }
-
- public override int PasswordAttemptWindow {
- get {
- throw new NotImplementedException();
- }
- }
-
- public override MembershipPasswordFormat PasswordFormat {
- get {
- throw new NotImplementedException();
- }
- }
-
- public override string PasswordStrengthRegularExpression {
- get {
- throw new NotImplementedException();
- }
- }
-
- public override bool RequiresQuestionAndAnswer {
- get {
- throw new NotImplementedException();
- }
- }
-
- public override bool RequiresUniqueEmail {
- get {
- throw new NotImplementedException();
- }
- }
-
- public override string ResetPassword(string username, string answer) {
- throw new NotImplementedException();
- }
-
- public override bool UnlockUser(string userName) {
- throw new NotImplementedException();
- }
-
- public override void UpdateUser(MembershipUser user) {
- throw new NotImplementedException();
- }
-
-
-
-
- public override bool ValidateUser(string username, string password) {
-
- using(RBACEntities dc = new RBACEntities()) {
- var user = dc.Users.Where(a = > a.Username.Equals(username) && a.Password.Equals(password)).FirstOrDefault();
- if (user != null) {
- return true;
- }
- }
- return false;
- }
- }
- }
Step 10: Web Config File.