/// <summary> /// 生成token,并存于redis,同时新增一条sessionlog记录 /// </summary> /// <param name="user"></param> /// <param name="sys"></param> /// <param name="ip"></param> /// <returns>是否成功</returns> private async Task <bool> SetTokenAsync(UserInfoAndRoleRight user, AppSystem sys, string ip) { var utcNow = DateTime.UtcNow; var token = SSOHelper.GenerateToken(user.UserInfo.UserID.ToString(), user.UserInfo.AccountName, user.UserInfo.UserName, ip); int timespan = ConfigService.TokenOverTime;//分钟 #region 缓存token var tokenKey = ConfigService.GetTokenRedisKey(user.UserInfo.UserID.ToString(), user.UserInfo.AccountName, sys.SystemCode); //检查当前用户在当前system下是否已有token。已有则更新log,并在redis中覆盖原有token var existTokenValue = redisCache.Get(tokenKey).ToString(); var userInfoKey = ConfigService.GetUserInfoRedisKey(token, sys.SystemCode); //缓存、db记录。 redisCache.Set(tokenKey, token, TimeSpan.FromMinutes(timespan)); redisCache.Set(userInfoKey, user, TimeSpan.FromMinutes(timespan)); //检查是否缓存成功 var cacheResult = redisCache.Get(tokenKey).ToString() == token && redisCache.Get(userInfoKey).ToString() == user.ToJson(); if (!existTokenValue.IsNullOrWhiteSpace()) { var existUserInfoKey = ConfigService.GetUserInfoRedisKey(existTokenValue, sys.SystemCode); redisCache.Remove(existUserInfoKey); //查询session日志记录 var sessionLog = await masterContext.UserSessionLogs.FirstOrDefaultAsync(a => a.UserToken == existTokenValue && a.UserID == user.UserInfo.UserID); if (sessionLog != null) { sessionLog.RealExpirationTime = utcNow; } } #endregion 缓存token //DB记录token记录 await masterContext.UserSessionLogs.AddAsync(new UserSessionLog { AccessHost = ip, CreateTime = utcNow, ModifyTime = utcNow, SystemID = sys.ID, SystemName = sys.SystemName, UserID = user.UserInfo.UserID, UserToken = token, ValidTime = timespan * 60, RealExpirationTime = utcNow.AddMinutes(timespan) }); var dbSaveResult = await masterContext.SaveChangesAsync(); if (cacheResult && dbSaveResult > 0) { user.Token = token; return(true); } return(false); }
static void TokenTest( ) { var token = SSOHelper.GenerateToken("1", "boo", "boo", "127.0.0.1"); Console.WriteLine($"token = {token} \r\n"); List <string> list = null; var result = SSOHelper.IsTokenValid(token, out list); Console.WriteLine($"Token Valid Result = {result} ,list = {list.ToJson()}"); }