Prevent multiple logins

前端 未结 2 1381
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 05:41

I am trying to block multiple logins with the same user in my application.
My idea is to update the security stamp when user signin and add that as a Claim, then in eve

2条回答
  •  清歌不尽
    2020-12-01 06:01

    In the past I've used IAuthorizationFilter and static logged-in user collection to achieve this:

    public static class WebAppData
    {
         public static ConcurrentDictionary Users = new ConcurrentDictionary();
    }
    
    public class AuthorisationAttribute : FilterAttribute, IAuthorizationFilter {
    
        public void OnAuthorization(AuthorizationContext filterContext){
    
                ...
                Handle claims authentication
                ...
    
                AppUser id = WebAppData.Users.Where(u=>u.Key ==userName).Select(u=>u.Value).FirstOrDefault();
                if (id == null){
                    id = new AppUser {...} ;
                    id.SessionId = filterContext.HttpContext.Session.SessionID;
                    WebAppData.Users.TryAdd(userName, id);
                }
                else
                {
                    if (id.SessionId != filterContext.HttpContext.Session.SessionID)
                    {
                            FormsAuthentication.SignOut();
                            ...
                            return appropriate error response depending is it ajax request or not
                            ...
    
    
                    }
                } 
         }
    }
    

    On logout:

    WebAppData.Users.TryRemove(userName, out user)
    

提交回复
热议问题