Udemy

Asp.net mvc Check User is Logged In and authorized Before Access to Page

Saturday, August 02, 2014 0 Comments A+ a-

Hi,

today i am sharing that how you can implement something that needs to be executed before every action is called. In asp.net mvc every thing is action, so we have to check in web application if user is logged in or not to restrict the users to authenticate before they view or do some action.

i also came across this scenario where i needed to check that if user is logged in and also is user authorized to view this page, i implemented this using built- in feature of asp.net mvc which is CustomActionFilterAttribute.

 First of all we need to create class which inherits from ActionFilterAttribute class:

public class AuthorizationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string actionName = filterContext.ActionDescriptor.ActionName;
        string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

        if (filterContext != null)
        {
            HttpSessionStateBase objHttpSessionStateBase = filterContext.HttpContext.Session;
            var userSession = objHttpSessionStateBase["userId"];
            if (((userSession == null) && (!objHttpSessionStateBase.IsNewSession)) || (objHttpSessionStateBase.IsNewSession))
            {
                objHttpSessionStateBase.RemoveAll();
                objHttpSessionStateBase.Clear();
                objHttpSessionStateBase.Abandon()
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                   filterContext.HttpContext.Response.StatusCode = 403;
                   filterContext.Result = new JsonResult { Data = "LogOut" };
                }
                else
                {
                   filterContext.Result = new RedirectResult("~/Home/Index");
                }

             }
             else
             {
                if (!CheckAccessRight(actionName, controllerName))
                {
                    string redirectUrl = string.Format("?returnUrl={0}", filterContext.HttpContext.Request.Url.PathAndQuery);
                    filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true);
                }
                else
                {
                    base.OnActionExecuting(filterContext);
                }
             }
       }
   }
}

 

Explanation:

Whenever any action will be called which is decorated with AuthorizationAttribute, our overriden method of  OnActionExecuting will be called.

First of all we are getting the controller and action name which is being called from the ActionExecutingContext object as it holds the context of the call:

string actionName = filterContext.ActionDescriptor.ActionName;
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

then i am getting the current Session and getting userId of current User which is stored in Session at the time of login:

HttpSessionStateBase objHttpSessionStateBase = filterContext.HttpContext.Session;
var userSession = objHttpSessionStateBase["userId"];

and after that i check that if  userId is null or the Session is new which means a new user has accessed the application, in that case clear all Session and abandon it::

objHttpSessionStateBase.RemoveAll();
objHttpSessionStateBase.Clear();
objHttpSessionStateBase.Abandon();

and redirect the user to login page, but before doing that we have two cases:

1) Normal Request
2)Ajax Request

So, we need to check that if it is a normal request simply redirect to login page, but if it is a ajax request then we will return json response that will tell at client side that it is not an authenticated request, and on client side after reading the response we can display user friendly message that "Please Login To Continue":

if (filterContext.HttpContext.Request.IsAjaxRequest())
{
     filterContext.HttpContext.Response.StatusCode = 403;
     filterContext.Result = new JsonResult { Data = "LogOut" };
}
else
{
     filterContext.Result = new RedirectResult("~/Home/Index");
}
To Be Continued.....................

Coursera - Hundreds of Specializations and courses in business, computer science, data science, and more