c# – Eliminate User Session in ASP.NET MVC with [Authorize]

Question:

I have a web system developed in ASP.NET MVC 4.

One of the features is user management. A CRUD of users.

My login method is as follows:

[HttpPost]
public ActionResult Login(LoginViewModel loginViewModel)
{
    if (_loginService == null)
        _loginService = new LoginService();

    var result = _loginService.Login(loginViewModel.User, loginViewModel.Password);
    if (!result.Error)
    {
        var userData = JsonConvert.SerializeObject(result.User);
        FormsAuthentication.SetAuthCookie(result.User.Id, false);
        var ticket = new FormsAuthenticationTicket(1, result.Id, DateTime.Now, DateTime.Now.AddMinutes(9999), true, userData, FormsAuthentication.FormsCookiePath);
        var encryptedCookie = FormsAuthentication.Encrypt(ticket);
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookie) { Expires = DateTime.Now.AddHours(14) };

        Response.Cookies.Add(cookie);
    }
    return new JsonResult
    {
        Data = result
    };
}

Yes, it is in English because the system will be maintained by several companies.

Anyway, I treat the return of this method on the client side, with javascript. As you can imagine, I use the [Authorize] attribute in every Controller where authentication is mandatory.

Let's say I just logged into the system with the StackOverflow user. I'm browsing normally until another user identified as DoMal decides to exclude me from the system. As I'm just deleting the user in the Delete action, the StackOverflow user will browse the site normally even when deleted. Until, of course, the cookie expires. Problem is, I want some way to end his session right away.

Is there any way to end the StackOverflow -only session in IIS? Or force the cookie to expire?

The only thing I don't want to do is create an online user existence check on every action taken on the site.

Any idea, suggestion?

Answer:

You have to implement your own Authorize Attribute. You can reuse the existing implementation and derive from the authorize attribute and make the modifications you need:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        if (actionContext.RequestContext.Principal != null &&
            actionContext.RequestContext.Principal.Identity.IsAuthenticated)
        {
            //o utilizador está autenticado, mas será que ainda existe na base de dados?

            var userName = actionContext.RequestContext.Principal.Identity.Name;
            object user = null;  //aqui faz consulta na base de dados por userName
            if (user == null) //se o utilizador nao existe, apaga o cookie
            {
                FormsAuthentication.SignOut();
            }

        }
        base.HandleUnauthorizedRequest(actionContext);
    }
}

I can't guarantee that this code will work the first time, but it should give you an idea of ​​what to do.

Scroll to Top