Search This Blog

Friday, July 13, 2018

MVC 4: How to create Login Form and Restrict User for browsing some page/ How to apply Authorization attributes to web



Now After registering User now write code for login.
How to create a custom role-based page authorization using custom Authorize filter
For achieving above target
First change in web.cofig
  <system.web>   
  <authentication mode="Forms">
      <forms loginUrl="~/UserLog/Login"   defaultUrl="~/Home/Welcome"></forms>
    </authentication>
  </system.web>

First Add Properties For View
Add code in viewProperties.cs

public class UserLoginView
    {
        [Key]
        public int UserID { get; set; }
        [Required(ErrorMessage = "*")]
        [Display(Name = "User Name")]
        public string LoginName { get; set; }
        [Required(ErrorMessage = "*")]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
    }

Now add method for view (if any)
Retrieve password from Database for the User, for this we are going to add method in methodManager class
   public string GetPassword(string UserName)
        {
            using (StoreDBContext  db = new StoreDBContext ())
            {
                var user = db.UsersLogins.Where(m =>
                m.Username.ToLower().Equals(UserName));
                if (user.Any())
                    return user.FirstOrDefault().Password ;
                else return string.Empty;
            }
        }
Now we need controller for login we need two actionresult method one for get and other for post.
Now add link for log off also in welcome page
@Html.ActionLink("Log Out", "LogOut", "UserLog")

Login.cshtml
@model StoreManagementSystem.Models.PropertiesForView.LoginView

@{
    ViewBag.Title = "LogIn";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>LogIn Page</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <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">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="LogIn" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to Home", "Index", "Home")
</div>

<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Now check out the development till yet.

Now let’s start work for Role Based Page. I.e. according to user authority we provide user for particular section or restrict for particular section.
So the question is
How to Implementing a Simple Role-Based Page Authorization

Authorization specifies access rights to a certain resource or page. In our example we are having a page that only a certain user role can have access to it. For example, only allow administrator to access the maintenance page. In this section we will know how to achieve that.

For this let’s add some methods and properties
Check for the role of user , add code in methodmenager.
In method add following code
public bool IsRoleExist(string username, string roleName)
        {
            using (StoreDBContext  db = new StoreDBContext ())
            {
                UsersLogin usersLogin = db.UsersLogins.Where(m =>
                m.Username.ToLower().Equals(username))?.FirstOrDefault();
                if (usersLogin != null)
                {
                    var roles = from q in db.UserRoles
                                join r in db.UserRoleDetails on q.RoleID
                                equals r.RoleID
                                where q.RoleName.Equals(roleName) && q.UserID.Equals(usersLogin.Id)
                                select q.RoleName;

                    if (roles != null)
                    {
                        return roles.Any();
                    }
                }

                return false;
            }
        }

Add folder Sequrity to root directory
Add class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using StoreManagementSystem.Models.DataBase;
using StoreManagementSystem.Models.MethodForView;

namespace StoreManagementSystem.Sequrity
{
    public class AuthorizationAttribute : AuthorizeAttribute 
    {
        private readonly string[] RoleGranted;

        public AuthorizationAttribute(params string[] rolesgranted)
        {
            this.RoleGranted = rolesgranted;
        }

        protected override bool AuthorizeCore(HttpContextBase httpContextBase )
        {
            bool authorize = false;
            using (StoreDBContext  db = new StoreDBContext())
            {
                MethodManager methodManager  = new MethodManager();
                foreach (var roles in RoleGranted)
                {
                    authorize = methodManager.IsRoleExist(httpContextBase.User.Identity.Name, roles);
                    if (authorize) return authorize;
                }
            }
            return authorize;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext authorizationContext )
        {
            authorizationContext.Result = new RedirectResult("~/Home/UnAuthorized");
        }

    }
}


Now add control action in home controller
Add directives to home controller
using System.Web.Security;

add code

[Authorization("Admin")]  //Only Admin can go through this page
        public ActionResult AdminOnly()
        {
            return View();
        }

        public ActionResult UnAuthorized()
        {
            return View();
        }
Now add View to Control
Adimonly.cshtml

@{
    ViewBag.Title = "AdminOnly";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Hi <b>@Context.User.Identity.Name</b>  You are authorized for the page ..</h2>
<div>

    @Html.ActionLink("Back to Main", "Welcome", "Home")
</div>


UnAuthorized.cshtml


@{
    ViewBag.Title = "UnAuthorized";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Not Authorised , hi <b>@Context.User.Identity.Name</b>  , You are not Autharised for the Page..</h2>

<div>

    @Html.ActionLink("Back to Main", "Welcome", "Home")
</div>

Test the Page....

No comments:

Post a Comment