MVC Check Session variable, sign out, and redirect globally

Upon logging in, I am saving a Session variable for that user who just logged in. This Session variable is very very important for every single thing the user then see's (see this question MVC Individual User Accounts login value persisting)

I see there being a potential problem where the Session variable is not tied in with the user being logged in, it has its own expiry (unless someone can give a 100% fool proof way of that NOT happening, for example, when I restart debugging, I am still logged in but the session variable has gone, regardless of expiry).

What I do then, is to check the Session variable exists, and sign them out and redirect if its null. However the redirect needs to be done within the Action, and would need to happen for EVERY get request, so there will be a lot of duplicate code.

var customerIdSession = Session["CustomerId"];
if (customerIdSession == null)
{
     // Then sign out which needs the AuthenticationManager property to be defined in the controller too!
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); 

     return RedirectToAction("Login", "Account");
}
var customerId = Convert.ToInt32(customerIdSession);

Is there a way I could tidy this up? And not have to do this on EVERY get method. Make it a global check somehow, like Authorize does for login

Answers


I found the answer on my own in the end. I took the idea I had of it being similar to the Authorize so found a way to make my own Authrorize attribute. This way, I can put the attribute above every Controller then assume the Session variable exists in every action. If not, the user is logged out and redirected automatically.

public class AuthorizeSessionAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var customerId = httpContext.Session["CustomerId"];

        if (customerId == null)
        {
            var lo = httpContext.GetOwinContext().Authentication;
            lo.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

            return false;
        }

        return true;
    }
}

Need Your Help

Fabric.js: How to draw a polygon by mouse

fabricjs

I want draw a fabric.Polygon with mouse interaction in Fabric.js.

Custom Layout not Displaying at all - Android

android android-layout android-studio android-custom-view

I am going through a code in order to display a custom view (circle draw) on a Camera preview. It builds fine with no Errors but problem is that Custom view is not showing. I am perhaps making a mi...