用redis和cookie做單用戶登錄


因為公司的項目需要用到單用戶登錄,於是今天用redis和cookie給系統添加了單用戶登錄功能,再次簡單記錄一下。

單用戶登錄是為了防止同一賬戶在不同電腦和不同瀏覽器里面同時登錄。所以我這邊的思路是:

1.用戶登錄A賬號時,獲取A賬號信息和當前瀏覽器cookie里面的token信息結合起來存到redis數據庫。

2.有其他用戶登錄A賬號,更新redis里面的用戶信息和token信息,以最后一次登錄為准。

3.寫攔截器攔截每個請求,在處理請求時,判斷當前用戶信息與token數據和redis里面的數據是否一致,如果不一致,則說明該賬號在別的地方登陸過,則會提示重新登錄。

代碼如下:

在用戶登錄的方法里,寫如下代碼:將用戶登錄信息與瀏覽器token數據存入redis數據庫

//更新redis里面的用戶登錄信息
string userid = userEntity.F_UserId;
string companyId = userEntity.F_CompanyId;
string token =Request.Cookies["__RequestVerificationToken"].Value.ToString();
cache.Remove(cache_userloginid + userid, CacheId.loginInfo);
UserLoginEntity userLogin = new UserLoginEntity();
userLogin.UserLoginID = userid + "_" + companyId + "_" + token;
TimeSpan cacheTime = TimeSpan.FromDays(1);
cache.Write<UserLoginEntity>(cache_userloginid + userid, userLogin, cacheTime, CacheId.loginInfo);
               

寫攔截器,在每次請求時判斷當前用戶信息與token數據和redis里面的數據是否一致,根據結果做出反應

public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // 判斷當前登錄信息是否存在
            string userid = LoginUserInfo.Get() == null ? "" : LoginUserInfo.Get().userId;
            string companyId = LoginUserInfo.Get() == null ? "" : LoginUserInfo.Get().companyId;
            string token = HttpContext.Current.Request.Cookies["__RequestVerificationToken"] == null ? "" : HttpContext.Current.Request.Cookies["__RequestVerificationToken"].Value.ToString();
            UserLoginEntity userLogin = cache.Read<UserLoginEntity>(cache_userloginid + userid, CacheId.loginInfo);
            if (userLogin != null)
            {
                //有用戶登陸中
                string userLoginId = userLogin.UserLoginID; //redis中保存的用戶登錄標識
                string myuserLoginId = userid + "_" + companyId + "_" + token;
                if (userLoginId != myuserLoginId)
                {
                    //兩個用戶標識不一樣
                    filterContext.Result = new ContentResult()
                    {
                        Content = "<script>" +
                                  "if(confirm('你的賬號已在別處登陸,是否返回登陸頁面?')){window.location.href='/Login/Index';}else{window.close();}</script>"
                    };
                }
            }

            base.OnActionExecuting(filterContext);
        }

如果信息不一致,則說明在之后還有人登陸過該賬號,則會彈出提示:

以上就是我做這個功能的思路以及部分代碼。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM