Asp.Net MVC Membership Provider to Create Users, Roles & Mapping Roles to Users

  Total Views : 4865
  Comments : 1
 
  Keywords : Create users in Asp.net mvc membership provider, Asp.net mvc custom membership provider to create roles, Mapping users to roles in asp.net mvc membership, Role based security in asp.net mv

Here we will learn membership provider in asp.net mvc, create users, roles using asp.net mvc membership, assign roles to users in asp.net mvc membership provider, remove users from roles in asp.net mvc membership, get all roles / users from asp.net mvc membership and implement security in asp.net mvc applications with examples.

Security in Asp.Net MVC

To secure applicaiton in asp.net mvc we need to implement security mechanism. By using following methods in asp.net mvc we can implement security in applications.

 

  1. Authentication & Authorization in asp.net mvc
  2. Membership providers in asp.net mvc
  3. Roles based authentication in asp.net mvc

The most major part of any web application is to secure it and provide role base access to users. For this Microsoft has built in Authentication & Authorization Mechanism called as ASP .NET MVC Membership Provider. Here we will see what is authorization and authentication in asp.net mvc

 

Authentication: In simple words we can say check whether user is valid or not.

 

Authorization: It means  giving permission to access or deny particular resources or pages for user.

 

We will see how to create database schema for Asp.net MVC Membership provider along with that Registration of User and creating Role and Assigning role to Registered Users in asp.net mvc with demos.

 

Let’s create a simple application and learn how to implement asp.net mvc membership provider.

Create New Asp.Net MVC Application

Let's start with creating new asp.net mvc 4 application for that Open visual studio studio à Go to File à Select New à Select Project

 

create new asp.net mvc project from visual studio 2012

 

After that you will see new dialog will pop up for selecting your Template and Project type. From Templates select Visual C# à inside that select Web and then project type select ASP.NET MVC 4 Web Application and here we are giving name as “DemoAuth” then finally click on OK button

 

select asp.net mvc 4 web application and click ok to create new mvc application

 

After naming and click on OK button now new dialog will pop up for selecting template in that Select Internet Application template and set view engine as Razor and we are not going to create Unit testing for this project hence do not check this option and finally click OK like as shown below

 

select internet application template for asp.net mvc authentication project

 

After click wait for some time it requires some seconds for configuring solution for you. After creating project our project will be ready and it contains whole lot MVC folder structure and other script and .css style like as shown below

 

Security & Authentication application in asp.net mvc

 

After successfully creating application now let’s move towards creating Database.

Create Database

Now create database in SQL Server with any name but we are naming it “DemoAuth

 

create new database in sql server for asp.net mvc authentication example

 

After creating database that will be like as shown below 

 

newly created database structure in asp.net mvc

 

After creating Database with name “DemoAuth” now let's add connection string to project

 

<connectionStrings>

<add name="DBConnectionconnectionString "Data Source=sai-pc;Database=DemoAuth;UID=sa;Password=Pass$123providerName="System.Data.SqlClient" />

</connectionStrings>

After adding the connection string now let's add Membership tables to the DemoAuth database. Before that let’s have look at model (AccountModels) and it's located in Models Folder which is created Default if you are choosing Internet Application Template that will be like as shown below

 

Account Models File in Models folder in asp.net mvc application 

AccountModels file will contain code like as shown below

 

Account Models file code structure in asp.net mvc

 

InitializeDatabaseConnection in Global.asax for Creating Membership tables

Here we are going to Use Code First Approach of Entity Framework. Now for adding Membership tables to database we need to add a single line of following code in Global.asax

 

WebSecurity.InitializeDatabaseConnection("DBConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

The above line will create all Membership tables for this method we need to provide parameters like as shown above. Following is the brief descript about InitializeDatabaseConnection method

 

InitializeDatabaseConnection Method Metadata

 

public static void InitializeDatabaseConnection (string connectionStringName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables);

Parameters

 

Following are the parameters we used intializedatabaseconneciton method

 

connectionStringName: The name of the connection string for the database that contains user information. If you are using SQL Server Compact, this can be the name of the database file (.sdf file) without the .sdf file name extension.

        

userTableName: The name of the database table that contains the user profile information.

        

userIdColumn: The name of the database column that contains user IDs. This column must be typed as an integer (int).

        

userNameColumn: The name of the database column that contains user names. This column is used to match user profile data to membership account data.

        

 autoCreateTables: True to indicate that user profile and membership tables should be created if they do not exist; false to indicate that tables should not be created automatically. Although the membership tables can be created automatically, the database itself must already exist.

 

Once we add our database conneciton in our Global.asax file that will be like as shown below

 

Global.asax file in asp.net mvc applicaiton with database conneciton

 

Finally after all configuration now let’s run application and check. After running application you will find Default homepage on that page at right corner you will find register link just click on it and wait for some time a Register page will popup like as shown below

 

registration page to create asp.net mvc membership tables in database

 

Now after popping up of Register page have look on database which we have created “DemoAuth” just expand database and inside table you will see all Membership Tables are created.

 

Database tables with asp.net mvc membership tables

Registration Page in Asp.Net MVC using Membership Provider

After clicking on Register page here is view of it.

 

Adding columns in UserProfile table

In this Register View we only take few details while Registering User lets add some more fields such as FirstName, LastName, EmailID, Address, MobilePhone. For that we need to add new columns in “UserProfile” table.

 

User Profile table in asp.net mvc membership provider

Making changes in RegisterModel

After adding new columns in UserProfile table now we need to do this change in RegisterModel also. Register Model file will be located inside Account Models and Account Models which is created by Default if you are choosing Internet Application Template.

 

making modification in registermodel file in asp.net mvc membership provider

 

In this RegisterModel we made changes to add properties to Register Model (FirstName, LastName, EmailID, Address, MobilePhone). After making modifications in RegisterModel that will contain code like as shown below

 

public class RegisterModel

{

[Required]

[Display(Name = "User name")]

public string UserName { get; set; }

 

[Required]

[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.",

MinimumLength = 6)]

 

[DataType(DataType.Password)]

[Display(Name = "Password")]

public string Password { get; set; }

 

[DataType(DataType.Password)]

[Display(Name = "Confirm password")]

[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]

public string ConfirmPassword { get; set; }

 

[Required]

[Display(Name = "First Name")]

public string FirstName { get; set; }

 

[Required]

[Display(Name = "Last Name")]

public string LastName { get; set; }

 

[Required]

[Display(Name = "EmailID")]

public string EmailID { get; set; }

 

[Required]

[Display(Name = "Address")]

public string Address { get; set; }

 

[Required]

[Display(Name = "MobilePhone")]

public string MobilePhone { get; set; }

}

After doing this changes in RegisterModel lets do changes similar Changes in Register View. In this Register View we are going to add those fields which we have added in RegisterModel that will be like as shown below 

 

Register view page in asp.net mvc membership provider

 

Now we completed doing changes with Model and View only still Controller part is remaining. 

Making Changes in Register Action Method

According to changes made in Register Model and Register View we need to make changes in Register Action Method also.

 

Register Action Method is Located inside Account Controller and we are going to make change in the Register Action method which handle [HttpPost] Request. Let’s make changes in Register Action Method. 

 

According to Old RegisterModel we have below line to Register User.

 

WebSecurity.CreateUserAndAccount(model.UserName, model.Password);

 

Now we are going to add more Fields to it.

 

WebSecurity.CreateUserAndAccount(model.UserName, model.Password,

new

{

FirstName = model.FirstName,

LastName = model.LastName,

EmailID = model.EmailID,

Address = model.Address,

MobilePhone = model.MobilePhone

});

Complete Code snippet for Register Action Method (Post).

 

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public ActionResult Register(RegisterModel model)

{

if (ModelState.IsValid)

{

// Attempt to register the user

try

{

WebSecurity.CreateUserAndAccount(model.UserName, model.Password,

new

{

FirstName = model.FirstName,

LastName = model.LastName,

EmailID = model.EmailID,

Address = model.Address,

MobilePhone = model.MobilePhone

});

 

WebSecurity.Login(model.UserName, model.Password);

return RedirectToAction("Index", "Home");

}

catch (MembershipCreateUserException e)

{

ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));

}

}

// If we got this far, something failed, redisplay form

return View(model);

}

After making changes now run application to register user. Use following format of url like "http://localhost:2180/Account/Register" to view new user registration form. 

 

New user registration form in asp.net mvc membership application

 

After Registering User look in database that will contain details we added in table like as shown below.

 

after creating new user in asp.net mvc membership application

 After Registering User now let’s move towards Creating Roles in asp.net mvc.

Create Roles in Asp.Net MVC Membership

For Creating Roles first we need to add a Model with name Role and we are going to Add Role Model inside Account Models which is inside Models Folder.

 

[Table("webpages_Roles")]

public class Role

{

[Required(ErrorMessage = "Enter Role name")]

[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]

public string RoleName { get; set; }

 

[Key]

[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

public int RoleId { get; set; }

}

After Creating Model now let’s add Action Method with Name “RoleCreate” for both Http Request in Account Controller.

 

[HttpGet]

public ActionResult RoleCreate()

{

return View(new Role());

}

 

[HttpPost]

public ActionResult RoleCreate(Role role)

{

return View(role);

}

After adding RoleCreate Action Method now lets Add View for RoleCreate Action Method.

Adding RoleCreate View

Before adding View just build application and then Right click inside RoleCreate Action Method and select Add View menu from list after selecting  new Dialog will popup with Dialog Name “Add View” then View name of this View will be RoleCreate the name of Action Method inside which we have Right click to Add.

 

In View engine we are going to set Razor as View engine and in Model class we are going to set Role as our Model for this View. In Scaffolding Template we are going to select Create Template and finally set Use a layout or master page option by checking it like as shown below 

 

create new view for role creation in asp.net mvc application

 

Finally click on Add View button. After clicking on this button it will create a View in Account Folder with Name “RoleCreate”.

 

After adding role create model in asp.net mvc application

 

Now let’s run our application you will see login page just enter User details which we have created and then hit this URL  "http://localhost:1096/Account/RoleCreate" then RoleCreate View will appear that will be like as shown below.

 

create new role in asp.net mvc application

 

After appearing View now we need to write code for Insert role in our Database for that we need to write Code for RoleCreate [HttpPost] Action Method. Inside this Action Method we have built in method to check Roles are exists or not [Roles.RoleExists(role.RoleName) ] this method return Boolean value if this Role name Exits then We are going show error Rolename already exists else we are going insert Role it in to database by using in built Method [Roles.CreateRole(role.RoleName);].

 

Following is code snippet of RoleCreate [HttpPost] Method

 

[HttpPost]

public ActionResult RoleCreate(Role role)

{

if (ModelState.IsValid)

{

if (Roles.RoleExists(role.RoleName))

{

ModelState.AddModelError("Error", "Rolename already exists");

return View(role);

}

else

{

Roles.CreateRole(role.RoleName);

return RedirectToAction("RoleIndex", "Account");

}

}

else

{

ModelState.AddModelError("Error", "Please enter Username and Password");

}

return View(role);

}

In First Step we created User and in Second Step we created Role now in next step let’s display all Roles which we have added.

Displaying all Roles Added

For displaying all roles we are going to use Code First Approach. Let’s start using Code First Approach for that first thing we are going to created Class with name UsersContext. This UsersContext class is created Default if you are choosing Internet Application and it is located at Top Most in Account Models.

If you want to create manually then below are step to create it.

 

public class UsersContext

{

 

}

After Creating UsersContext class now implement DBContext and DbSet to interact with database and its operations. Here below is code of DbContext class.

 

public class UsersContext : DbContext

{

public UsersContext(): base("DBConnection")

{

}

public DbSet<Role> Roles { get; set; }

}

DBConnection - Here it is a Name of Connection string in Web.config file.

 

After Adding UsersContext now let’s create a Action Method with Name DisplayAllRoles. In this Action Method we are going access all the roles which we have added. Here below is code of DisplayAllRoles Action Method which is located inside Account Controller.

 

[HttpGet]

public ActionResult DisplayAllRoles()

{

return View();

}

Now let’s add logic to this Action Method for displaying all Roles.

 

[HttpGet]

public ActionResult DisplayAllRoles()

{

IEnumerable<Role> ListRoles;

using (UsersContext db = new UsersContext())

{

ListRoles = db.Roles.ToList();

}

return View(ListRoles);

}

Now we have completed DisplayAllRoles Action Method part let’s add View with Name DisplayAllRoles. For adding view you just need to right Click inside Action Method DisplayAllRoles after that a new Dialog will Popup with Name Add View. Folllowing is the snapshot of adding view with properties

 

Add view to show all roles in asp.net mvc application

 

In above dialog the View Name will be similar to Action Method .then View engine will be Razor default. For now we are not going to select Model here manually we are going to Add Model namespace on view. Finally just click on Add button. After adding a blank View will appear now we are  going to display role for that we need grid to display those roles for that we will Add Grid.MVC in this Project from Nuggets Package Manager.

Adding Grid.MVC

For Adding Grid.MVC just right click on Project and select Manage NuGet Packages

 

installing nuget package in asp.net mvc application

 

After clicking on Manage NuGet Packages a new dialog will popup as show below

 

Install Grid.MVC in asp.net mvc application

 

Now in left side list select Online panel inside that select Search Results. Now in search box type Grid.MVC and click on Install button. After installing it will show a Green symbols with Right Mark like as shown below

 

After installing grid.mvc in asp.net mvc application

 

After adding Grid.MVC let's move back to where we have left DisplayAllRoles View.

Adding Grid.MVC to DisplayAllRoles View

For this view we are going to use model Role and from Action Method we are sending List of Role for that I will use IEnumerable<Role>.

 

Passing Model to View @model IEnumerable<DemoAuth.Models.Role>

 

For using Grid.MVC we need to add namespace @using GridMvc.Html

 

In Grid we are going display 2 Columns

 

  1. Role ID
  2. RoleName

Following is the code snippet of DisplayAllRoles View

 

@model IEnumerable<DemoAuth.Models.Role>

@using GridMvc.Html

@{

ViewBag.Title = "DisplayAllRoles";

}

 

<h2>DisplayAllRoles</h2>

 

<link href="~/Content/Gridmvc.css" rel="stylesheet"/>

<link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>

<script src="~/Scripts/jquery-1.9.1.min.js"></script>

<script src="~/Scripts/gridmvc.js"></script>

 

@Html.Grid(Model).Columns(columns =>

{

columns.Add(c => c.RoleId).Titled("Role ID");

columns.Add(c => c.RoleName).Titled("RoleName").Filterable(true);

}).WithPaging(10).Sortable(true)

Now let’s save application and run to access DisplayAllRoles View. To access use URL like "http://localhost:2180/Account/DisplayAllRoles" and it will display all the roles we added

 

Show all roles in asp.net mvc application

 

Finally we displayed all Roles which we have added now let's Move towards assigning this roles to User.

Assigning Role to User in Asp.Net MVC Membership

For Assigning role to Member we first need to create Model which will have MemberList and RoleList from this list we are going to assign role to Users. Let’s begin with Adding Model with Name AssignRoleVM we are going to Add AssignRoleVM Model inside Account Models which is inside Models Folder.

 

public class AssignRoleVM

{

[Required(ErrorMessage = " Select Role Name")]

public string RoleName { get; set; }

[Required(ErrorMessage = "Select UserName")]

public string UserID { get; set; }

public List<SelectListItem> Userlist { get; set; }

public List<SelectListItem> RolesList { get; set; }

}

After creating Model now let’s add New Action Method with Name RoleAddToUser inside Account Controller

 

[HttpGet]

public ActionResult RoleAddToUser()

{

 

}

In this action Method we are going add MemberList and RoleList which will be used on View to bind Dropdownlist.

 

Adding new DbSet in UserContext

 

We are going to add DbSet UserProfile inside UsersContext

 

public DbSet<RegisterModel> UserProfile { get; set; }

 

In DBContext we added new DbSet UserProfile

 

public class UsersContext : DbContext

{

public UsersContext()

: base("DBConnection")

{

}

public DbSet<Role> Roles { get; set; }

public DbSet<RegisterModel> UserProfile { get; set; }

 

}

Creating GetAll_Roles Method

 

We created GetAll_Roles Method for getting all Role from Database and return RolesList and this Method is created inside Account Controller.

 

[NonAction]

public List<SelectListItem> GetAll_Roles()

{

List<SelectListItem> listrole = new List<SelectListItem>();

listrole.Add(new SelectListItem { Text = "select", Value = "0" });

using (UsersContext db = new UsersContext())

{

foreach (var item in db.Roles)

{

listrole.Add(new SelectListItem { Text = item.RoleName, Value = item.RoleName });

}

}

return listrole;

}

Creating GetAll_Users Method

 

We created GetAll_Users Method for getting all Users from Database and return Userlist and this Method is created inside Account Controller.

 

[NonAction]

public List<SelectListItem> GetAll_Users()

{

List<SelectListItem> listuser = new List<SelectListItem>();

listuser.Add(newSelectListItem { Text = "Select", Value = "0" });

 

using (UsersContext db = new UsersContext())

{

foreach (var item in db.UserProfile)

{

listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });

}

}

return listuser;

}

Assigning value to AssignRoleVM Model

 

Now let’s assign this value to AssignRoleVM Model in RoleAddToUser Action Method.

 

[HttpGet]

public ActionResult RoleAddToUser()

{

AssignRoleVM objvm = new AssignRoleVM();

objvm.RolesList = GetAll_Roles();

objvm.Userlist = GetAll_Users();

return View(objvm);

}

After assigning Value now let’s add A View. For adding view you just need to right Click inside Action Method RoleAddToUser a new Dialog will Popup with Name Add View

 

View to assign roles to users in asp.net mvc application

 

In above image the View Name will be similar to Action Method .and View engine will be Razor default. For now we are going to select AssignRoleVM Model. After that in scaffold template we are going to select Create Template and finally click on Add button. 

 

After adding it will create a View with Name same as Action Method (RoleAddToUser) but in this view we have to make change by changing default code and add DropdownList. 

 

Here is the code of (RoleAddToUser View) in which we added DropdownList by removing textboxes which where generated by Create Template. Following is the Code snippet of RoleAddtoUser View.

 

@model DemoAuth.Models.AssignRoleVM

@{

ViewBag.Title = "RoleAddToUser";

}

<h2>RoleAddToUser</h2>

<link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>

<script src="~/bootstrap/js/bootstrap.min.js"></script>

@using (Html.BeginForm())

{

@Html.ValidationSummary(true)

@Html.AntiForgeryToken()

 

<div>

@ViewBag.ResultMessage

</div>

<fieldset>

<legend>AssignRoleVM</legend>

 

<div class="editor-label">

@Html.LabelFor(model => model.RoleName)

</div>

<div class="editor-field">

@Html.DropDownListFor(m => m.RoleName, new SelectList(Model.RolesList, "Value", "Text"),

new { style = "width:200px", @class = "form-control" })

@Html.ValidationMessageFor(model => model.RoleName)

</div>

 

<div class="editor-label">

@Html.LabelFor(model => model.UserID)

</div>

<div class="editor-field">

@Html.DropDownListFor(m => m.UserID, new SelectList(Model.Userlist, "Value", "Text"),

new { style = "width:200px", @class = "form-control" })

@Html.ValidationMessageFor(model => model.UserID)

</div>

<br/>

<p>

<input type="submit" value="Assign"/>

</p>

</fieldset>

}

<div>

@Html.ActionLink("Back to List", "Index")

</div>

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

}

Following is the snapshot after adding DropdownList to RoleAddToUser View. To access view we need to use url like " http://localhost:2180/Account/RoleAddToUser".

 

Assign roles to users in asp.net mvc membership provider 

After completing with rendering part now let’s work on its [HttpPost] Request Part of RoleAddToUser Action Method. Let's Add New Action Method with Name RoleAddToUser with [HttpPost] Request which will take AssignRoleVM Model as input to this Action Method.

 

RoleAddToUser Action Method 

 

We are going to add RoleAddtoUser Action Method inside Account Controller.

 

[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult RoleAddToUser(AssignRoleVM objvm)

{

 

}

After adding Action Method further we are going to add validation and Assigning role to User logic in this Action Method.

 

Validation inside RoleAddtoUser ActionMethod

 

First validation to check both dropdownlist are select or not.

 

if (objvm.RoleName == "0")

{

ModelState.AddModelError("RoleName", "Please select RoleName");

}

 

if (objvm.UserID == "0")

{

ModelState.AddModelError("UserName", "Please select Username");

}

Second validation to check whether any role is assign to User.

 

Creating Model of webpages_UsersInRoles table

 

For that we need to add new Model for Existing table (webpages_UsersInRoles). We are going to add webpages_UsersInRoles Model inside Account Models which is inside Models Folder.

 

[Table("webpages_UsersInRoles")]

public class webpages_UsersInRoles

{

[Key]

[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

public int UserId { get; set; }

 

public int RoleId { get; set; }

}

Adding webpages_UsersInRole DbSet in DBContext

 

We are going to add DbSet webpages_UsersInRole inside UsersContext.

 

public DbSet<webpages_UsersInRoles> webpages_UsersInRole { get; set; }

 

Method for checking whether any role is assign to User 

 

After adding model lets check whether any role is assign to User. If yes then count will be greater that one else it will be Zero ( 0 )

 

public bool Get_CheckUserRoles(int UserId)

{

using (UsersContext context = newUsersContext())

{

var data = (from WR in context.webpages_UsersInRole

join R in context.Roles on WR.RoleId equals R.RoleId

where WR.UserId == UserId

orderby R.RoleId

select new

{

WR.UserId

}).Count();

 

if (data > 0)

{

return true;

}

else

{

return false;

}

}

}

Now we have created Get_CheckUserRoles method and we are going to call this method before assigning role to use.

 

if (Get_CheckUserRoles(Convert.ToInt32(objvm.UserID)) == true)

{

ViewBag.ResultMessage = "This user already has the role specified !";

}

else

{

var UserName = GetUserName_BY_UserID(Convert.ToInt32(objvm.UserID));

Roles.AddUserToRole(UserName, objvm.RoleName);

ViewBag.ResultMessage = "Username added to the role successfully !";

}

In above condition user does not exists then we are going to assign roles to this User. Before assigning User to role we are getting UserName by UserID.

 

Method for getting UserName by UserID 

 

Here we Created GetUserName_BY_UserID Method for getting Users name from UserID and this Method is created inside Account Controller.

 

public string GetUserName_BY_UserID(int UserId)

{

using (UsersContext context = newUsersContext())

{

var UserName = (from UP in context.UserProfile

where UP.UserId == UserId

select UP.UserName).SingleOrDefault();

return UserName;

}

}

After explaining method used now let's Merge in Action Method

 

Code snippet for RoleAddToUser Action Method 

 

[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult RoleAddToUser(AssignRoleVM objvm)

{

if (objvm.RoleName == "0")

{

ModelState.AddModelError("RoleName", "Please select RoleName");

}

if (objvm.UserID == "0")

{

ModelState.AddModelError("UserName", "Please select Username");

}

if (ModelState.IsValid)

{

if (Get_CheckUserRoles(Convert.ToInt32(objvm.UserID)) == true)

{

ViewBag.ResultMessage = "This user already has the role specified !";

}

else

{

var UserName = GetUserName_BY_UserID(Convert.ToInt32(objvm.UserID));

Roles.AddUserToRole(UserName, objvm.RoleName);

ViewBag.ResultMessage = "Username added to the role successfully !";

}

objvm.RolesList = GetAll_Roles();

objvm.Userlist = GetAll_Users();

return View(objvm);

}

else

{

objvm.RolesList = GetAll_Roles();

objvm.Userlist = GetAll_Users();

}

return View(objvm);

}

 Now run application and access this page. You first need to login then access url "http://localhost:2180/Account/RoleAddToUser".

 

After entering URL you will find RoleAddToUser View on this view we have one dropdown for Users and another is for Roles select User and Roles and click on Assign button if User do not have any role then it will allow to assign role else it will show alert Message.

 

Assign roles to users in asp.net mvc membership provider

 

After assigning value now let’s have look on table where values of role assigned are stored. These values will be stored in webpages_UsersInRoles table

 

After mapping roles to users in asp.net mvc membership provider

 

Now we completed part of Role assigning to User let's create a new screen for displaying which role is assign to which User.

 

Creating View AllroleandUser

 

In this view we are just going to display role and user name for that we created a model with Name AllroleandUser. This Model will be added inside Account Models which is inside Models Folder

 

public class AllroleandUser

{

public string RoleName { get; set; }

public string UserName { get; set; }

public IEnumerable<AllroleandUser> AllDetailsUserlist { get; set; }

}

After adding Model next step we are going to add Action Method with name “DisplayAllUserroles” this will be only for [HttpGet] Request.

 

[HttpGet]

public ActionResult DisplayAllUserroles()

{

 

}

After adding DisplayAllUserroles Action Method Now we will write Linq query to get UserName and RoleName

 

[NonAction]

public List<AllroleandUser> Get_Username_And_Rolename()

{

using (UsersContext db = newUsersContext())

{

var Alldata = (from User in db.UserProfile

join WU in db.webpages_UsersInRole on User.UserId equals WU.UserId

join WR in db.Roles on WU.RoleId equals WR.RoleId

select new AllroleandUser { UserName = User.UserName, RoleName= WR.RoleName }).ToList();

 

return Alldata;

}

}

The above Linq query will return UserName and RoleName of all Users registered to whom Role are assign and in next step we are going to access this Method in DisplayAllUserroles Action Method and assign value to IEnumerable<AllroleandUser> model List. Following is the code snippet for DisplayAllUserroles Action Method inside Account Controller.

 

[HttpGet]

public ActionResult DisplayAllUserroles()

{

AllroleandUser objru = new AllroleandUser();

objru.AllDetailsUserlist = Get_Username_And_Rolename();

return View(objru);

}

After completing assigning value with in DisplayAllUserroles Action Method now let’s add View. For adding view you just need to right Click inside Action Method DisplayAllUserroles a new Dialog will Popup with Name Add View like as shown below

 

Add new view to show all users and roles in asp.net mvc membership provider

 

 

In above image the View Name will be similar to Action Method then View engine will be Razor default. For now we are going to select AllroleandUser Model.and in scaffold template we are going to select Empty Template and finally click on Add button.

 

After clicking on add button a Blank View with selected model namespace will be seen now in this View we are going to display UserName and RoleName of all Users using Grid.MVC.

 

@model DemoAuth.Models.AllroleandUser

@using GridMvc.Html

@{

ViewBag.Title = "DisplayAllUserroles";

}

<h2>DisplayAllUserroles</h2>

<link href="~/Content/Gridmvc.css" rel="stylesheet"/>

<link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>

<script src="~/Scripts/jquery-1.9.1.min.js"></script>

<script src="~/Scripts/gridmvc.js"></script>

@Html.Grid(Model.AllDetailsUserlist).Columns(columns =>

{

columns.Add(c => c.UserName).Titled("UserName").Filterable(true);

columns.Add(c => c.RoleName).Titled("RoleName").Filterable(true);

}).WithPaging(10).Sortable(true)

Now run DisplayAllUserroles View using url like "http://localhost:2180/Account/DisplayAllUserroles"

 

Display all users and roles in asp.net mvc membership provider

 

Finally after displaying All User roles and name now let’s think to remove from role in next step. It will be similar to allocating Role to User.

Remove Assigned Users from Role in Asp.Net MVC

Now let’s start with Creating Last View Remove Role from User. In this Action Method we are going to remove Role from User to whom we have allocated Role. The View for this Action Method will be similar to RoleAddToUser View in this View we are going to see 2 dropdownlist one will be for User and another will be for Role.

 

Adding Action Method with Name RemoveRoleAddedToUser in this Action Method we are going to use same model (AssignRoleVM) which we have already used for RoleAddToUser. In [HttpGet] request we are going to fill both dropdownlist of User and Role. 

 

Following is the code snippet to add RemoveRoleAddedToUser Action Method inside Account Controller

 

[HttpGet]

public ActionResult RemoveRoleAddedToUser()

{

AssignRoleVM objvm = new AssignRoleVM();

objvm.RolesList = GetAll_Roles();

objvm.Userlist = GetAll_Users();

return View(objvm);

}

After creating Action Method RemoveRoleAddedToUser for handling [HttpGet] request now we are going to add another Action Method with similar name RemoveRoleAddedToUser for handling [HttpPost] request and this Action Method will have AssignRoleVM Model as Input Parameter.

 

Now we are going to add RemoveRoleAddedToUser Action Method inside Account Controller

 

[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult RemoveRoleAddedToUser(AssignRoleVM objvm)

{

return View();

}

After adding Action Method now we are going to add logic and Validation to it. First thing let’s check the user which we are going to remove is existing in role or not. For checking user existence we have created a method which take UserID as input and checks User exists or not and return Boolean value as output.

 

If User exists in role then we are going to remove role from user by using in built Membership method [ Roles.RemoveUserFromRole ] for this method we need to pass to 2 parameter first UserName and second RoleName like as shown below

 

Roles.RemoveUserFromRole(UserName, objvm.RoleName);

Following is the code snippet to check whether user exists in role or not 

 

if (Get_CheckUserRoles(Convert.ToInt32(objvm.UserID)) == true)

{

var UserName = GetUserName_BY_UserID(Convert.ToInt32(objvm.UserID));

Roles.RemoveUserFromRole(UserName, objvm.RoleName);

ViewBag.ResultMessage = "Role removed from this user successfully !";

}

else

{

ViewBag.ResultMessage = "This user doesn't belong to selected role.";

}

In above code we are going to check if user to whom we are assigning role is already in role or not if he is in role then we are going to execute  if part of code in that we are going to Remove role of User and show Message [ViewBag.ResultMessage = "Role removed from this user successfully !";] else if User is not in role than we are going to execute else part of code and going to show Message  e.g. [ViewBag.ResultMessage = "This user doesn't belong to selected role."; ]. Following is the code snippet of RemoveRoleAddedToUser Action Method

 

[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult RemoveRoleAddedToUser(AssignRoleVM objvm)

{

if (objvm.RoleName == "0")

{

ModelState.AddModelError("RoleName", "Please select RoleName");

}

if (objvm.UserID == "0")

{

ModelState.AddModelError("UserName", "Please select Username");

}

if (ModelState.IsValid)

{

if (Get_CheckUserRoles(Convert.ToInt32(objvm.UserID)) == true)

{

var UserName = GetUserName_BY_UserID(Convert.ToInt32(objvm.UserID));

Roles.RemoveUserFromRole(UserName, objvm.RoleName);

ViewBag.ResultMessage = "Role removed from this user successfully !";

}

else

{

ViewBag.ResultMessage = "This user doesn't belong to selected role.";

}

objvm.RolesList = GetAll_Roles();

objvm.Userlist = GetAll_Users();

}

else

{

objvm.RolesList = GetAll_Roles();

objvm.Userlist = GetAll_Users();

}

return View(objvm);

}

After creating Action Method now we are going to Add View (RemoveRoleAddedToUser). For adding view you just need to right Click inside Action Method RemoveRoleAddedToUser a new Dialog will Popup with Name Add View. Following is the snapshot of RemoveRoleAddedToUser View

 

View to remove roles from user in asp.net mvc membership provider

 

In above dialog the View Name will be similar to Action Method .then View engine will be Razor default. For now we are going to select AssignRoleVM Model. After that in scaffold template we are going to select Create Template and finally click on Add button. 

 

After adding it will create a View with Name same as Action Method (RemoveRoleAddedToUser) but in this view we have to make change by changing default code and add DropdownList. Here is the code of (RemoveRoleAddedToUser View) in which we added DropdownList by removing textboxes which where generated by Create Template. Following is the code snippet of RemoveRoleAddedToUser View

 

@model DemoAuth.Models.AssignRoleVM

@{

ViewBag.Title = "RoleAddToUser";

}

<h2>RoleAddToUser</h2>

<link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>

<script src="~/bootstrap/js/bootstrap.min.js"></script>

@using (Html.BeginForm())

{

@Html.ValidationSummary(true)

@Html.AntiForgeryToken()

<div>

@ViewBag.ResultMessage

</div>

<fieldset>

<legend>AssignRoleVM</legend>

<div class="editor-label">

@Html.LabelFor(model => model.RoleName)

</div>

<div class="editor-field">

@Html.DropDownListFor(m => m.RoleName, newSelectList(Model.RolesList, "Value", "Text"),

new { style = "width:200px", @class = "form-control" })

@Html.ValidationMessageFor(model => model.RoleName)

</div>

<div class="editor-label">

@Html.LabelFor(model => model.UserID)

</div>

<div class="editor-field">

@Html.DropDownListFor(m => m.UserID, newSelectList(Model.Userlist, "Value", "Text"),

new { style = "width:200px", @class = "form-control" })

@Html.ValidationMessageFor(model => model.UserID)

</div>

<br/>

<p>

<input type="submit" value="Remove Role"/>

</p>

</fieldset>

}

<div>

@Html.ActionLink("Back to List", "Index")

</div>

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

}

Now access run application and access RemoveRoleAddedToUser View using url like "http://localhost:2180/Account/RemoveRoleAddedToUser"

 

Remove role added to users in asp.net mvc membership provider

 

Adding Authorize Attribute to Controller and ActionMethod

If you want to authorize entire Controller then Apply [Authorize] Attribute to Controller and if you want only for some action Method then apply to Action Method only. Let's checkout [Authorize] Attribute with Controller. For that we are going to add 2 Controller for Demo.

 

  1. Demo1Controller
  2. Demo2Controller

Adding Controller

 

For Adding Controller just Right click on Controller Folder select Add à then select Controller. As you select controller a new dialog will popup Add Controller. 

 

After this let's give Name to Controller “Demo1Controller”. In template we are not going to select any template for that we are selecting “Empty MVC controller” then click on Add Button.

 

After creating controller For Demo1Controller I have added [Authorize] Attribute to entire Controller if user is having role of “Admin” can only access this controller else it will redirect to Login Page.

 

In this example we showed Authorize Attribute with Rolename [Authorize(Roles="Admin")] if you want to Authorize Attribute with Username then you need to use Users [Authorize(Users = "TestAdmin")].

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace DemoAuth.Controllers

{

[Authorize(Roles="Admin")]

public class Demo1Controller : Controller

{

public ActionResult Index()

{

return View();

}

}

}

Now we will add new controller for that Right click on Controller Folder select Add à then select Controller. As you select controller a new dialog will popup Add Controller. 

 

After this let's give Name to Controller “Demo2Controller”.In template we are not going to select any template for that we are selecting “Empty MVC controller” then click on Add Button.

 

After creating controller For Demo2Controller we added [Authorize] Attribute to Action Method if user is having role of “Admin” can only access this Action Method else it will redirect to Login Page

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace DemoAuth.Controllers

{

public class Demo2Controller : Controller

{

[Authorize(Roles = "Admin")]

public ActionResult Index()

{

return View();

}

}

}

In Last if you want to Use Authorize Attribute with both combination of Rolename and Username then you can do in following way. In this Role must be “Admin” and login Username must be “TestAdmin” then only he can access this Action Method. E.g [Authorize(Roles = "Admin", Users = "TestAdmin")].

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace DemoAuth.Controllers

{

public class Demo2Controller : Controller

{

//

// GET: /Demo2/

[Authorize(Roles = "Admin", Users = "TestAdmin")]

public ActionResult Index()

{

return View();

}

}

}

Finally the View which we have created.

 

  1. Login
  2. Register
  3. RoleCreate
  4. DisplayAllRoles
  5. RoleAddToUser
  6. RemoveRoleAddedToUser
  7. DisplayAllUserroles

Following are the links of asp.net mvc membership.

 

Asp.net mvc membership provider links create user, role, assign user to role, delete role, user

 Comments (1)

  • xx xx tutlane registered profile image
     
    xx xx   Reply

    Thank you for the tutorial! I would like to know how to reproduce the same table/ design with buttons/links that you have in the last image

     Aug 15, 2016

Leave a comment

  • Default Tutlane User