Thumb

Part-6: Point of Sale(POS) Login and Authorization with Session variables in ASP.NET | JQUERY | AJAX

5/28/2020 12:00:00 AM

Download Project

Step-1:

  • Create a folder name “Helper” inside your project.
  • Create a class name “AuthorizationFilter” inside the “Helper” Folder.
  • Add below code into “AuthorizationFilter” class.
    public class AuthorizationFilter : AuthorizeAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            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();
            }
        }
    }

Step-2:

  • Replace your previous “CheckLogin” method inside Home controller by below code
        public JsonResult CheckLogin(string username,string password)
        {
            POS_TutorialEntities db = new POS_TutorialEntities();
            var dataItem = db.Users.Where(x => x.Username == username && x.Password == password).SingleOrDefault();
            bool isLogged = true;
            if (dataItem != null)
            {
                Session["Username"] = dataItem.Username;
                isLogged = true;
            }
            else
            {
                isLogged = false;
            }
            return Json(isLogged, JsonRequestBehavior.AllowGet);
        }
  • Change login path inside “Startup”>”ConfigureAuth”
LoginPath = new PathString("/Home/Login")
  • Put this below code in top of HomeController>Index method
[AuthorizationFilter]
  • Run the project

About Teacher

Reza Karim

Software Engineer

More about him