Role Based Authentication In ASP.NET MVC

Introduction :

This article will explain the role-based authentication in ASP.NET MVC with examples.In traditional web development with ASP.NET, we have been using Membership and Role providers. These providers allows us to define Roles, Users and assign roles to users which helps us to manage Authorization.

Step 1 :   First we have create class for role provider using this class we have set the roles and get  the roles as per requirement.

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();      
        }

Step 3 :  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

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 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 } };

        }
    }
}

Step 7 :  Now need to add we.config file as following

<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>
    <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>

Above  role provider code  tested and implemented, if you have query regarding Role Based Authentication In ASP.NET MVC  then feel free to contact.

SEE MORE

 

Leave a Reply

Your email address will not be published. Required fields are marked *