Click Here For MCQ

Wednesday, June 17, 2020

Asp.Net Mvc Role Base Authorisation and Authentication

Model(sql databasae related)


 public partial class tbl_user
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Role { get; set; }
    }


 public partial class tbl_trainee
    {
        public int sno { get; set; }
        public string trainee_name { get; set; }
        public string father_name { get; set; }
        public string department { get; set; }
        public string college { get; set; }
    }

  public partial class tbl_emp
    {
        public int Sno { get; set; }
        public string employeename { get; set; }
        public string fathername { get; set; }
        public string department { get; set; }
    }



login Controller

 public class LoginController : Controller
    {
    
        studentEntities db = new studentEntities();
        // GET: Login
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Account()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Account(tbl_user user)
        {
            var count = db.tbl_user.Where(x => x.UserName == user.UserName && x.Password == user.Password).Count();
            if (count !=0)
            {
                FormsAuthentication.SetAuthCookie(user.UserName,false);
                return RedirectToAction("Itraineelist", "Home");
            }
            else
            {
                TempData["msg"] = "username & password is incorrect";
                return View();    
            }
            return View();
        }
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("About", "Home");
        }
        
    }
}

home controller




    public class HomeController : Controller
    {
        studentEntities db = new studentEntities();
        [AllowAnonymous]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "V, A")]
        public ActionResult Indexlist()
        {
            var emp = db.tbl_emp.ToList();
            return View(emp);
        }
        public ActionResult empcreate()
        {
            return View();

        }

        [HttpPost]
        public ActionResult empcreate(tbl_emp emp)
        {
            db.tbl_emp.Add(emp);
            db.SaveChanges();
            return View();
        }
        [Authorize(Roles ="V")]
        public ActionResult Itraineelist()
        {
            var emp = db.tbl_trainee.ToList();
            return View(emp);
        }

        public ActionResult traincreate()
        {
            return View();

        }
        [HttpPost]
        public ActionResult traincreate(tbl_trainee trainee)
        {
            db.tbl_trainee.Add(trainee);
            db.SaveChanges();
            return View();
        }
        [AllowAnonymous]
        public ActionResult About()
        {
            return View();
        }
        [AllowAnonymous]
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}













Account View


@model MyloginProject.Models.tbl_user

@{
    ViewBag.Title = "Account";
}

<h2>Account</h2>


@using (Html.BeginForm("Account", "Login", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>tbl_user</h4>

        @TempData["msg"]
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        @*<div class="form-group">
            @Html.LabelFor(model => model.Role, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Role, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Role, "", new { @class = "text-danger" })
            </div>
        </div>*@

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Login" class="btn btn-primary" />
            </div>
        </div>
    </div>
}



@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Indexlist view


@model IEnumerable<MyloginProject.Models.tbl_emp>

@{
    ViewBag.Title = "Indexlist";
}

<h2>Indexlist</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.employeename)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.fathername)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.department)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.employeename)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.fathername)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.department)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Sno }) |
            @Html.ActionLink("Details", "Details", new { id=item.Sno }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Sno })
        </td>
    </tr>
}

</table>




layout view 




<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    @if (User.Identity.IsAuthenticated == true)
                    {
                        <li>@Html.ActionLink("Create Employee", "empcreate", "Home")</li>

                        <li>@Html.ActionLink("Create Trainee", "traincreate", "Home")</li>
                        if (User.IsInRole("V,A"))
                        {
                        <li>@Html.ActionLink("EMPLOYEE List", "Indexlist", "Home")</li>
                        }
                        if (User.IsInRole("V"))
                        {
                            <li>@Html.ActionLink("Trainee List", "Itraineelist", "Home")</li>
                        }
                         <li>@Html.ActionLink("Logout", "Logout", "Login")</li>

                         <li><a href="#">@User.Identity.Name</a></li>
                    }
                    else
                    {
                         <li>@Html.ActionLink("Login", "Account", "Login")</li>
                    }


                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>




















solution web.config



 <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <authentication mode="Forms">
      <forms loginUrl="Login/Account">
        
      </forms>
      
    </authentication>
  <roleManager enabled="true" defaultProvider="MyRoleProvider">
    <providers>
      <clear/>
      <add name="MyRoleProvider" type="MyloginProject.MyRoleProvider"/>
    </providers>
  </roleManager>
  </system.web>



my role provider.cs


using MyloginProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace MyloginProject
{
    public class MyRoleProvider : RoleProvider
    {
        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }

            set
            {
                throw new NotImplementedException();
            }
        }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            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)
        {
            studentEntities db = new studentEntities();
            string[] role = { db.tbl_user.Where(x => x.UserName == username).FirstOrDefault().Role};
            return role;
        }

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

No comments:

Post a Comment