Role Based Authentication Of in MVC Application
Introduction : when we have some user with different access level with same application then we need to prevent some access of pages with different user so that time we need to use role based authentication. so we can prevent admin pages to the client access.Step 1: Create Role provider class
MyRoleProvider.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
namespace Mvc_SP
{
public class MyRoleProvider:RoleProvider
{
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)
{
System.Web.SessionState.HttpSessionState session = HttpContext.Current.Session;
string stRole = session["Type"] == null ? "4" : session["Type"].ToString();
string[] results = { stRole };
return results;
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override bool IsUserInRole(string username, string roleName)
{
throw new NotImplementedException();
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}
Step 2: Create login form and Store Session variable
[HttpPost]
public ActionResult Login(AuthModel da)
{
SqlCommand cmd = new SqlCommand("sp_login", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Name", SqlDbType.VarChar);
cmd.Parameters.Add("@Password", SqlDbType.VarChar);
cmd.Parameters["@Name"].Value = da.Name;
cmd.Parameters["@Password"].Value = da.Password;
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
Name = row["Name"].ToString();
Type = Convert.ToInt16(row["UType"]);
Parentid = Convert.ToInt16(row["Parentid"]);
Pkid = Convert.ToInt16(row["Pkid"]);
FormsAuthentication.SetAuthCookie(da.Name, false);
}
return RedirectToAction("Index");
}
return View();
}
Step3 : Create Index Page
@model Mvc_SP.Models.AuthModel
@{
ViewBag.Title = "Index";
}
@ViewBag.type
<p style="color:red;">@(Request.IsAuthenticated ? HttpContext.Current.User.Identity.Name : "")</p>
<h2>Index</h2>
@Html.ActionLink("Test page", "Test")
Step 4 : Create Register page
@model Mvc_SP.Models.AuthModel
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script>
function Data() {
var ct = document.getElementById('ddlUserType');
var Type = ct.options[ct.selectedIndex].value;
var Name = $("#Name").val();
var Password = $("#Password").val();
$.ajax({
url: '@Url.Action("Register")',
data: { Name: Name, Password: Password, Type: Type },
type: 'POST',
dataType: 'json',
success: function (result) {
if (result.status) {
alert(result.message);
window.location.href = result.Url;
}
else {
alert(result.message);
}
}
});
}
</script>
@{
ViewBag.Title = "Register";
}
<h2>Register</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>AuthModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</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">
User Type
</div>
<div class="editor-field">
<div>
@Html.DropDownListFor( m => m.Utype, (SelectList) ViewBag.Utype, new { @id = "ddlUserType", @class = "form-control" } )
</div>
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Block)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Block)
@Html.ValidationMessageFor(model => model.Block)
</div>
<p>
<input type="button" value="Create" onclick="Data();" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Step 5 : Create model Class
public class AuthModel
{
public int Pkid { get; set; }
public string Name { get; set; }
public int Parentid { get; set; }
public string Password { get; set; }
public byte Utype { get; set; }
public bool Block { get; set; }
}
Step 6: now create AuthController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using Mvc_SP.Models;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;
namespace Mvc_SP.Controllers
{
public class AuthController : SessionController
{
//
// GET: /Auth/
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conAuth"].ConnectionString);
public ActionResult Index()
{
ViewBag.type = Type;
return View();
}
[Authorize(Roles="0,1")]
[HttpGet]
public ActionResult Test()
{
ViewBag.type = Type;
return View();
}
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpGet]
public ActionResult error()
{
return View();
}
[HttpPost]
public ActionResult Login(AuthModel da)
{
SqlCommand cmd = new SqlCommand("sp_login", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Name", SqlDbType.VarChar);
cmd.Parameters.Add("@Password", SqlDbType.VarChar);
cmd.Parameters["@Name"].Value = da.Name;
cmd.Parameters["@Password"].Value = da.Password;
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
Name = row["Name"].ToString();
Type = Convert.ToInt16(row["UType"]);
Parentid = Convert.ToInt16(row["Parentid"]);
Pkid = Convert.ToInt16(row["Pkid"]);
FormsAuthentication.SetAuthCookie(da.Name, false);
}
return RedirectToAction("Index");
}
return View();
}
[HttpGet]
public ActionResult Register()
{
DataTable dtTypes = DTable;
if (dtTypes == null)
{
dtTypes = new DataTable();
dtTypes.Columns.Add("stType", typeof(string));
dtTypes.Columns.Add("btValue", typeof(byte));
if (Type == 0)
{
AddUserType(dtTypes, "SUPER", 1);
AddUserType(dtTypes, "MASTER", 2);
}
else if (Type == 1)
{
AddUserType(dtTypes, "MASTER", 2);
AddUserType(dtTypes, "USER", 3);
}
else if (Type == 2)
{
AddUserType(dtTypes, "USER", 3);
}
DTable = dtTypes;
}
IEnumerable<SelectListItem> typelist = new SelectList(DTable.AsDataView(), "btValue", "stType");
ViewBag.Utype = typelist;
return View();
}
void AddUserType(DataTable dt, string stType, byte btValue)
{
DataRow drN = dt.NewRow();
drN["stType"] = stType;
drN["btValue"] = btValue;
dt.Rows.Add(drN);
}
[HttpPost]
public ActionResult Register(string Name,string Password,string Type)
{
bool blSucceeded = false;
string reply = "";
con.Open();
SqlCommand cmd = new SqlCommand("sp_register", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Parentid", SqlDbType.Int);
cmd.Parameters.Add("@Name", SqlDbType.VarChar);
cmd.Parameters.Add("@Block", SqlDbType.VarChar);
cmd.Parameters.Add("@Utype", SqlDbType.VarChar);
cmd.Parameters.Add("@Password", SqlDbType.VarChar);
cmd.Parameters["@Parentid"].Value = Pkid;
cmd.Parameters["@Name"].Value = Name;
cmd.Parameters["@Block"].Value = "false";
cmd.Parameters["@Utype"].Value = Type;
cmd.Parameters["@Password"].Value = Password;
cmd.ExecuteNonQuery();
con.Close();
blSucceeded = true;
reply = "User Added Successful";
return new JsonResult { Data = new { status = blSucceeded, Url = "/Auth/Index", message = reply } };
}
}
}
Web.Config :
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
<authentication mode="Forms">
<forms loginUrl="~/Auth/error" timeout="2880" slidingExpiration="true"></forms>
</authentication>
<!--<customErrors mode="On" defaultRedirect="~/Auth/">
<error statusCode="404" redirect="~/Auth/error" />
<error statusCode="401" redirect="~/Auth/error" />
</customErrors>-->
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<roleManager defaultProvider="MyRoleProvider" enabled="true">
<providers>
<add name="MyRoleProvider" type="Mvc_SP.MyRoleProvider, Mvc_SP" />
</providers>
</roleManager>
</system.web>
See Other Tutorial :
* AngularJS CRUD Operation : Select Insert Edit Update and Delete using AngularJS in ASP.Net MVC
* AngularJS With ASP.NET MVC
* Convert Rows to columns using 'Pivot' in SQL Server
* Mvc Registration page With user exist using Ajax method
* MVC 4 How to Perform Insert Update Delete Edit Select Operation
* MVC4 Edit,update,Delete,cancel inside gridview using sql database
* MVC 4 Gridview To Display Data Using SQL Server Database With Simple code
* Login page in asp.net Mvc4 Web application
* Mvc4 How to bind Dropdown List using Sql Database
* Gridview find control in asp.net
Sign up here with your email
1 comments:
Write commentsphân pһối chung cư ѵincity
ReplyConversionConversion EmoticonEmoticon