Thumb

Part-8: Point of Sale(POS) Role based authentication and authorization in ASP.NET MVC|Redirect to not found page if not authorized|C#

7/4/2020 12:00:00 AM

Download Project

See previous article/video before starting this

Step-1:

  • Create a table name “RolePermission”
  • Table property will be like below

                     Id - int – Primary key with auto incremented

                     Role - String

                     Tag – String

  • Table create script is given below
CREATE TABLE [dbo].[RolePermission](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Role] [nvarchar](50) NULL,
	[Tag] [nvarchar](50) NULL,
 CONSTRAINT [PK_RolePermission] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
  • Update new added table to ADO.NET Entity data model by refreshing [for more see the video]

Step-2:

  • Add a new Action-Method named “AccessDenied” inside the Home controller.
       public ActionResult AccessDenied()
        {
            return View();
        }
  • Add a view named “AccessDenied.cshtml” under “Home” folder. Paste this below code
@{
    ViewBag.Title = "AccessDenied";
}

<h2>You are not authorized!</h2>
  • Replace below code to AuthorizationFilter class
public void OnAuthorization(AuthorizationContext filterContext)
        {
            POS_TutorialEntities db = new POS_TutorialEntities();
            string username = Convert.ToString(System.Web.HttpContext.Current.Session["Username"]);
            string role = Convert.ToString(System.Web.HttpContext.Current.Session["Role"]);
            string actionName = filterContext.ActionDescriptor.ActionName;
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string tag = controllerName + actionName;

            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
                || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                // Don't check for authorization as AllowAnonymous filter is applied to the action or controller
                return;
            }

            // Check for authorization
            if (System.Web.HttpContext.Current.Session["Username"] == null)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
            if (username != null && username != "")
            {
                bool isPermitted = false;

                var viewPermission = db.RolePermissions.Where(x => x.Role == role && x.Tag == tag).SingleOrDefault();
                if (viewPermission != null)
                {
                    isPermitted = true;
                }
                if (isPermitted == false)
                {
                    filterContext.Result = new RedirectToRouteResult(
                      new RouteValueDictionary  
                        {  
                             { "controller", "Home" },  
                             { "action", "AccessDenied" }
                        });
                }
            }
        }
  • If you use [AuthorizationFilter] on top of any view then it will check this users role permitted for this view or not?. If not then it will redirect to AccessDenied  page.
  • Now provide the access for a Role to a View in “RolePermission” Table. [for better understand see the video]
  • Run the project [see videos for more clarification]

About Teacher

Reza Karim

Software Engineer

More about him