Question

My application let me to create,edit and delete user after I log-out. Although I have created session variable soon after user get authenticated and also removed it on log-out. However in mvc4 I am unable to figure out where to check these session variable condition( null or not). Like in asp.net(c#)page_load was the page where we could implement if condition.

Throughout internet people were discussing about disabling browser back button with java script and also deleting cookies but in my case once user logs out and if he uses browser back button to look the content and if clicked it should redirect to log in page.

Can somebody assist me in finding the right place to check the condition for session variable null or not. Is it view? Is it share_layout view? Or is it controller? Or something else I have no hint please help.

Here is my session controller code

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult LogIn(User user)
    {
        try
        {
            if (ModelState.IsValid)
            {
                var userdb = db.User.Include("Role").Single(c => c.userName == user.userName);
                if (userdb.passWord == user.passWord)
                {
                    Session["UserId"] = userdb.userId;
                    Session["UserName"] = userdb.userName;
                    Session["RoleName"] = userdb.Role.roleName;


                    if (userdb.Role.roleName == "Employee")
                    {
                        return RedirectToAction("Index", "Employee");
                    }
                    else if (userdb.Role.roleName == "Customer")
                    {
                        return RedirectToAction("Index", "CustomerSite");
                    }
                    else if (userdb.Role.roleName == "Admin")
                    {
                        return RedirectToAction("Index", "Admin");
                    }
                }
 else
                {
                    ViewBag.errorMsg = "We cannot authenticate you please use the right username or password";
                    return View();
                }
            }
            return View();
        }

And for Log-out

 public ActionResult Logout()
    {
        Session.Remove("UserId");
        Session.Remove("UserName");
        Session.Remove("RoleName");
        return RedirectToAction("LogIn", "Session");

    }
Was it helpful?

Solution

Theoretically you want to use FormAuthentication. It works with default AuthorizeAttribute out of the box.

If you want to implement your own logic, you can override AuthorizeAttribute.

Here the example -

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    private bool AuthorizeUser(AuthorizationContext filterContext)
    {
        bool isAuthorized = false;

        if (filterContext.RequestContext.HttpContext != null)
        {
            var context = filterContext.RequestContext.HttpContext;

            if(context.Session["UserId"] != null)
                 isAuthorized = true;
        }
        return isAuthorized;
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
            throw new ArgumentNullException("filterContext");

        if (AuthorizeUser(filterContext))
                return;       

        base.OnAuthorization(filterContext);
    }    
}

Usage

[MyAuthorizeAttribute]
public class MyController : Controller
{
   ...
}

OTHER TIPS

Your problem is not really about where to check session. Usually you can check session value anywhere in your actions. Even though Session.Remove(key) deletes the entry, you can still find the key in the collection.

I'm assuming you're using form authentication in your project. With your logout action, the form authentication is still alive, that's why when you click browser back button, you still can create, edit and delete. You can change your logout action like below:

public ActionResult Logout()
    {
        Session.Clear();
        FormsAuthentication.SignOut();
        return RedirectToAction("Login", "Account");
    }

And aside from what you are doing, I would suggest implementing "return url", see below example: redirect to return url after login

Add 'Session.abandon' to your logout action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top