时间:2022-07-19 10:18:11 | 栏目:.NET代码 | 点击:次
/// <summary> /// 创建token /// </summary> /// <returns></returns> [HttpPost] public IActionResult CreateJWT1() { //创建声明Token数组 var claim = new Claim[] { new Claim("userid","123"), new Claim("userCode","kevinMa"), new Claim("projectID","62"), new Claim("isValid","1"), new Claim("userName","马鹏"), new Claim("address","深圳"), new Claim("datetime",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), new Claim("expires",DateTime.Now.AddHours(1).ToString("yyyy-MM-dd HH:mm:ss")), }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yanglingcong@qq.com"));//密钥大小要超过128bt,最少要16位 //实例化一个token对象 //第一种方式 //var token = new JwtSecurityToken(claims: claim); //第二种方式 var token = new JwtSecurityToken( issuer: "kevin",//发起人:当前项目 audience: "kevin project",//订阅:我们需要谁去使用这个Token claims: claim,//声明的数组 expires: DateTime.Now.AddHours(1),//当前时间加一小时,一小时后过期 signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)//数字签名 第一部分是密钥,第二部分是加密方式 ); //生成token var jwtToken = new JwtSecurityTokenHandler().WriteToken(token); return ToSuccessJson(new { token = jwtToken }); }
/// <summary> /// 解析token /// </summary> /// <param name="token"></param> /// <returns></returns> [HttpPost] public IActionResult JXToken(string token) { //第一种直接用JwtSecurityTokenHandler提供的read方法 var jwtHander = new JwtSecurityTokenHandler(); JwtSecurityToken jwtSecurityToken = jwtHander.ReadJwtToken(token); GetTokenModel tokenModel = new GetTokenModel(); var currentInfo = jwtSecurityToken.Claims; if (currentInfo.Count() > 0) { tokenModel.userid = currentInfo.FirstOrDefault(f => f.Type == "userid").Value; tokenModel.userCode = currentInfo.FirstOrDefault(f => f.Type == "userCode").Value; tokenModel.projectID = currentInfo.FirstOrDefault(f => f.Type == "projectID").Value; tokenModel.userName = currentInfo.FirstOrDefault(f => f.Type == "userName").Value; tokenModel.address = currentInfo.FirstOrDefault(f => f.Type == "address").Value; tokenModel.datetime = currentInfo.FirstOrDefault(f => f.Type == "datetime").Value; tokenModel.expires = currentInfo.FirstOrDefault(f => f.Type == "expires").Value; } return ToSuccessJson(new { tokenModel }); }