Wednesday, 18 January 2017

,

Role base authorization in MVC


In any application authentication and authorization is most important part.If it is not working fine then rest of the things dosen’t any mean.So in this blog i will tell you just basic things that how to manage our apllication having different types of roles.


Task Requirement:

Consider that we have to create an application for hotel management.There are four types of users is there Admin,Table Manager,Kitchen Manager,Cash Manager.Admin can access all the screen,Table Manager can access only table screen,Kitchen Manager can access only kitchen screen,Cash Manager can access only cash screen.So lets look into details.

Tools:Visual Studio 2015

Development:

Create new project  >> Web >> ASP.NET Web Application





Then Select  MVC from ASP.NET 4.6.1 templates list,


Select_template-1.png


As highlighted in above image select ‘Individual User Accounts’ as a Authentication type which is default selected then click OK.




references.png










By default identity,Owin,Entity Framework and many more packages included  which you can find under references.


















Goto View and open Server Explorer (Ctrl+Alt+S).


server_expo.png


You can see there is no any database is there under ‘Data Connections’.There is one question comes up in mind,If there is no database is there then where should I store user credential.Here the magic done by identity and entity freamwork.When our application run and first time any user did sucessfull registration then automatically database with specific table of identity has been created.

Let's go to visual studio and run our application,


Homepage.png 


As you can see Register tab which highlighted on right side,click on that.





registration.png 



It will open registration page like above,please enter email id and appropriate password then click on Register button.

Again open the server explorer and now you can see tables which are not present as before. 




server_expo.png

    
                                                                               

As you can see in above image  there are six tables was created after first successful registration.But right now we just talk about AspNetRoles, AspNetUserRoles and AspNetUsers tables.











Tables
Description
AspNetUsers
Contain user credential.
AspNetRoles
Contain application roles like Admin,CashManager etc.
AspNetUserRoles
Contain mapping of users and roles.

We will see all other tables and its functionality in upcoming blogs.


use_tbl.png

 
As shown in image of  AspNetUsers table we did the registration for four user through our application.





role_table.png                                                                                               
As shown in above image of AspNetRoles table we did the manually entry for four types of roles.




 user_role_map.png











Now,It's time to mapping both this table in AspNetUserRoles table.





We mapped the users with roles according to below,

User
Role
a@a.com
Admin(1)
t@t.com
TableManager(2)
k@k.com
KitchenManager(3)
c@c.com
CashManager(4)
 
 Yuppee…..Here we have completed database portion.No more further database task is remaning as per our application requirment.


Open the  App_Start folder and create ‘CustomAuthorize’ class as per below


public class CustomAuthorize : AuthorizeAttribute
   {
       protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
       {
           if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
           {
               base.HandleUnauthorizedRequest(filterContext);
           }
           else
           {
               filterContext.Result = new RedirectToRouteResult(new
               RouteValueDictionary(new { controller = "Home", action = "UnAuthorize" }));
           }
       }
   }

Instead of inbuilt  Authorize attributes we have created our custom attributes ‘CustomAuthorize’ which is inherited from ‘AuthorizeAttribute’ as per above.

       

Now time to utilize ‘CustomAuthorize’ ,Open HomeController inside the controller folder and add below code.

             [CustomAuthorize(Roles = "Admin,TableManager")]
       public ActionResult Table()
       {
           return View();
       }

       [CustomAuthorize(Roles = "Admin,KitchenManager")]
       public ActionResult Kitchen()
       {
           return View();
       }

       [CustomAuthorize(Roles = "Admin,CashManager")]
       public ActionResult Cash()
       {
           return View();
       }

       [CustomAuthorize(Roles = "Admin,TableManager,KitchenManager,CashManager")]
       public ActionResult UnAuthorize()
       {
           return View();
       }


Here three different action Table,Kitchen and Cash are accessible with user having appropriate role like Table action can accessible by Admin and TableManage user,Kitchen action can accessible by Admin and KitchenManager user.And we have created one more action UnAuthorize,If user having role of CashManager try to access Table action then it transfer to UnAuthorize action.


Create a view as per below,



For Table action

@{
    ViewBag.Title = "Table";
}
<h2>You are on Table-Manager page...</h2>

For Kitchen action

@{
    ViewBag.Title = "Table";
}
<h2>You are on Table-Manager page...</h2>

For Cash action

@{
    ViewBag.Title = "Table";
}
<h2>You are on Cash-Manager page...</h2>


For UnAuthorize action.
@{
    ViewBag.Title = "UnAuthorize";
}
<h2>You are unauthorize to access this page.</h2>


Now open Views >> Shared >> _Layout.cshtml and add below code after 
‘@Html.ActionLink("Contact", "Contact", "Home")’.

     
@{
                        if (HttpContext.Current.User.IsInRole("Admin") ||   
     !HttpContext.Current.User.Identity.IsAuthenticated)
                        {
                            <li>@Html.ActionLink("Table", "Table", "Home")</li>
                            <li>@Html.ActionLink("Kitchen", "Kitchen", "Home")</li>
                            <li>@Html.ActionLink("Cash", "Cash", "Home")</li>
                        }
                        else if (HttpContext.Current.User.IsInRole("TableManager"))
                        {
                         <li>@Html.ActionLink("Table", "Table", "Home")</li>
                        }
                        else if (HttpContext.Current.User.IsInRole("KitchenManager"))
                        {
                         <li>@Html.ActionLink("Kitchen", "Kitchen", "Home")</li> 
                        }
                        else if (HttpContext.Current.User.IsInRole("CashManager"))
                        {
                         <li>@Html.ActionLink("Cash", "Cash", "Home")</li> 
                        }

                    }
            


All Done.Run your application.


Here we develop basic level of role base authentication which make you help in understanding the basic concept and with help of this  you can implement role base authentication in you application.



Share:

0 comments:

Post a Comment