0

I need to prevent users logging into my ASP.NET MVC application from multiple sessions, and found this answer how to do it.

Now I want to add an MVC twist: some of the public methods on the Controller are unprotected, and I don't care who accesses them, and some are protected by an [Authorize] attribute to ensure that only logged-in users can access them. Now I want to customize the AuthorizeAttribute so that all methods flagged with that attribute will do the no-multiple-login verification described in the related question, and throw some kind of LoggedInElsewhereException so that the client can understand if and why the check failed.

I'm sure it can be done, but how?

Community
  • 1
  • 1
Shaul Behr
  • 36,951
  • 69
  • 249
  • 387
  • wouldn't it be easier to automaticaly log them out of all sessions besides the last one? You just have to invalidate all the other sessions, and these sessions will just be non-authenticated. Obviously, the membership provider has to be changed to keep track and do invalidation, as described in the referenced topic. – Artemiy Sep 19 '11 at 18:45
  • @Artemiy - I didn't know you could do that. How? (Please post as an answer.) – Shaul Behr Sep 20 '11 at 17:17
  • hey @Shaul u asked very interesting question but your question is not very clear to me....however it is solved. r u trying to say that at a time one user can access your Authorize area. if some one has enter into your authorized area then other people will not be able to enter into or access that area until the previous user log out from that area. if i misunderstood then please rectify me to understand your requirement. thanks – Thomas Sep 02 '13 at 10:32

1 Answers1

4

Just derive your new attribute from AuthorizeAttribute and override OnAuthorization method. In the method do your "single session" checks first, then fall back to base implementation.

E.g.

public class CheckSessionAndAuthorizeAttribute : AuthorizeAttribute
{
    public override OnAuthorization(AuthorizationContext context)
    {
        //check session id in cache or database
        bool isSessionOK = CheckSession();

        if (!isSessionOK)
        {
            //can be View, Redirect or absolutely customized logic 
            context.Result = new MyCustomResultThatExplainsError();
            return;
        }

        //do base stuff
        base.OnAuthorization(context);
    }
}
ivan
  • 628
  • 5
  • 14
  • Thanks @ivan, only thing is that throwing an exception doesn't tell the client in any understandable way why they've been thrown off. It is important to me to be able to return a meaningful error, like for example returning a redirect to an explanation page, or something like that. Can that be done using an attribute like this? – Shaul Behr Sep 20 '11 at 18:38
  • Beautiful! Works like a dream! Thank you! – Shaul Behr Sep 21 '11 at 17:03