/// <summary> /// 创建MD5签名 字典按ASCII码升序排序后 拼接成url params格式进行MD5加密 /// </summary> /// <param name="dic">要签名参数字典</param> /// <returns>md5加密后的字符串</returns> public static string CreateSign(Dictionary <string, string> dic) { var stringA = ""; var resultDic = from obj in dic orderby obj.Key select obj; foreach (var keyValue in resultDic) { if (string.IsNullOrEmpty(keyValue.Value.Trim())) { continue; } stringA += keyValue.Key.Trim() + "=" + keyValue.Value.Replace("\r\n", "").Replace(" ", "").Replace("\\", "").Trim() + "&"; } var stringSignTemp = stringA + "key=" + key; var sign = StaticInfo.MD5Encrypt32(stringSignTemp).ToUpper(); return(sign); }
/// <summary> /// 创建一个Token /// </summary> /// <param name="jsonStr"></param> /// <returns></returns> public static ReturnClass CreatToken(string jsonStr) { ReturnClass rc = new ReturnClass(); try { JObject jObj = new JObject(); jObj = JObject.Parse(jsonStr); if (string.IsNullOrEmpty(jObj["UserName"].ToString()) || string.IsNullOrEmpty(jObj["Password"].ToString())) { rc.Msg = "参数为空"; rc.Code = Code.ERR_Sign; rc.Data = ""; return(rc); } string userName = jObj["UserName"].ToString(); //用户名 string password = StaticInfo.MD5Encrypt32(jObj["Password"].ToString()); //密码 //去数据库查询是否有合法 MySqlParameter[] sp = new MySqlParameter[2]; sp[0] = new MySqlParameter("@account", userName); sp[1] = new MySqlParameter("@password", password); var sqlselect1 = string.Format("select * from ws_system_admin where account=@account and pwd=@password"); //DataRow result=MySqlHelper.GetDataSet(MySqlHelper.Conn,CommandType.Text,sqlselect1,sp).Tables[0].Rows[0]; //DataTable dtneed=MySqlHelper.GetDataSet(MySqlHelper.Conn,CommandType.Text,sqlselect1,sp).Tables[0]; DataTable dataTable = MySqlHelper.GetDataSet(MySqlHelper.Conn, CommandType.Text, sqlselect1, sp).Tables[0]; if (dataTable.Rows.Count < 1) { rc.Msg = "用户名或密码错误"; rc.Code = Code.ERR_Sign; rc.Data = ""; return(rc); } DataRow result = dataTable.Rows[0]; //MySqlHelper.GetDataSet(MySqlHelper.Conn,CommandType.Text,sqlselect1,sp).Tables[0].Rows[0]; //SqlHelper.ExecuteDataRow( System.Data.CommandType.Text, "select * from [Base_Users] where UserName='******' and Password='******'"); if (result == null) //说明不存在 { rc.Msg = "用户不存在"; rc.Code = Code.ERR_Sign; rc.Data = ""; return(rc); } // //只要是一登陆先清除token // MemoryCachingHelper._cache.Remove(result["UserID"].ToString()); // //先判断下缓存中是否存在 这个地方必须拿token去获取 // if(MemoryCachingHelper.Exists(result["UserID"].ToString())) // { // rc.Msg = "成功!"; // rc.Code = Code.SUCCED; // rc.Data = (Token)MemoryCachingHelper.Get(result["UserID"].ToString()); // } // else//不存在才会去生成Token //登陆时先删除 var redisTokenFlag = result["id"].ToString() + result["account"].ToString(); if (RedisStaticHelper.Exists(redisTokenFlag)) { //先删除 var jwtTokenStr = RedisStaticHelper.Get(redisTokenFlag); RedisStaticHelper.Del(jwtTokenStr); RedisStaticHelper.Del(redisTokenFlag); } { //生成JWT //生成token Token tk = new Token(); tk.userName = result["account"].ToString(); tk.userID = result["id"].ToString(); tk.sub = "Client"; //距离上次登录的毫秒数 tk.Timestamp = Convert.ToString(DateTimeToStamp(DateTime.Now)); //DateTime.Now.ToString("yyyyMMddHHmmss"); //token生成规则 用户名 密码 时间戳 MD5加密 //tk.AccessToken = MD5Encrypt32(EmpID, password, tk.Timestamp); //存一下token DateTime UTC = DateTime.UtcNow; Claim[] claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, tk.sub), //Subject, new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), //JWT ID,JWT的唯一标识 new Claim(JwtRegisteredClaimNames.Iat, UTC.ToString(), ClaimValueTypes.Integer64), //Issued At,JWT颁发的时间,采用标准unix时间,用于验证过期 }; JwtSecurityToken jwt = new JwtSecurityToken( issuer: "TianTao", //jwt签发者,非必须 audience: tk.userName, //jwt的接收该方,非必须 claims: claims, //声明集合 expires: UTC.AddHours(12), //指定token的生命周期,unix时间戳格式,非必须 signingCredentials: new Microsoft.IdentityModel.Tokens .SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes("RayPI's Secret Key")), SecurityAlgorithms.HmacSha256)); //使用私钥进行签名加密 var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); //生成最后的JWT字符串 tk.AccessToken = encodedJwt; // int count = SqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, "update [Emp] set Token='" + tk.AccessToken + "' where EmpID='" + EmpID + "' and Pwd='" + password + "'"); // if (count < 1) // { // rc.Msg = "失败,重试"; // rc.Code = Code.SystemError; // rc.Data = ""; // return rc; // } rc.Msg = "成功!"; rc.Code = Code.SUCCED; rc.Data = tk; //将token 存入缓存 //MemoryCachingHelper.addMemoryCache(tk.AccessToken,tk,new TimeSpan(0,10,0),new TimeSpan(0,10,0)); RedisStaticHelper.Set(tk.AccessToken, tk.ToJson()); RedisStaticHelper.Set(tk.userID + tk.userName, tk.AccessToken); } return(rc); } catch (Exception ex) { StaticInfo.Log(ex.ToString()); rc.Msg = "违反了中央八项纪律"; rc.Code = Code.SystemError; rc.Data = ""; return(rc); } }