Delete user session in ASP.NET MVC with [Authorize]

Asked

Viewed 499 times

4

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

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

My method of login 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 attribute [Authorize] throughout Controller where authentication is mandatory.

Let’s assume I just logged into the system with the user StackOverflow. I am browsing normally until another user identified as DoMal resolves to delete me from the system. As I am only deleting the user in the action of Delete, the user StackOverflow will normally browse the site even when it is deleted. Until, of course, the cookie expires. The problem is I want some way to end his session right away.

Do you have any way to end the session StackOverflow in IIS? Or force the cookie to expire?

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

Any ideas, suggestions?

  • Here’s a start from where you can go. http://stackoverflow.com/questions/12379215/how-to-force-logout-user-when-his-her-username-is-changed-by-another-user

  • When the user is removed, you have access to his id (or something like that). What prevents you from calling Signout on that user? In this case you would "drop" this user only in the controller method that removes such a user. To handle the cookie, have you tried Formsauthentication.Setauthcookie(user, false)? If nothing works, Voce can do your checking in Application_beginrequest instead of spreading through the system.

  • @Video: Why the SignOut does not accept parameters.. I want to do the SignOut of a user other than the current. Yes, I already use the FormsAuthentication.SetAuthCookie(user, false). Regarding the implementation of beginRequest is just what I don’t want to do: At all request, validate the user’s existence in the database.

  • @Marllonnasser please, if the answer below is correct, please sign. thank you

  • @Thomaserichpimentel: The answer does not meet my specific need but would work in general.

1 answer

1

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

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 code will work at first, but it should give you an idea of what you should do.

  • but that would be on every request, right?

  • @Marllon Nasser Voce uses the attribute in the same way as Authorize. You can put it in controllers or actions

Browser other questions tagged

You are not signed in. Login or sign up in order to post.