c#中token的使用方法实例
时间:2022-10-03 11:33:59|栏目:.NET代码|点击: 次
token的存在意义
这是我初略了解的token的存在意义
- 用户使用用户名密码来请求服务器
- 服务器进行验证用户的信息
- 服务器通过验证发送给用户一个token
- 客户端存储token,并在每次请求时附送上这个token值
- 服务端验证token值,并返回数据
使用方法
先安装一个JWT,注意NetFramework的版本
创建一个工具类TokenInfo.cs
using JWT; using JWT.Algorithms; using JWT.Serializers; using System; using System.Collections.Generic; using System.Web; using System.Web.Script.Serialization; namespace ProjectLYG.Common { public class TokenInfo { public TokenInfo() { UserName = "j"; Pwd = "123456"; } public string UserName { get; set; } public string Pwd { get; set; } } public class TokenHelper { public static string SecretKey = "bqsid123k12s0h1d3uhf493fh02hdd102h9s3h38ff";//这个服务端加密秘钥 属于私钥 private static JavaScriptSerializer myJson = new JavaScriptSerializer(); /// <summary> /// 生成Token /// </summary> /// <param name="M"></param> /// <returns></returns> public static string GenToken(TokenInfo M) { var payload = new Dictionary<string, dynamic> { {"UserName", M.UserName},//用于存放当前登录人账户信息 {"UserPwd", M.Pwd}//用于存放当前登录人登录密码信息 }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); return encoder.Encode(payload, SecretKey); } /// <summary> /// 验证Token /// </summary> /// <returns></returns> public static string DecodeToken() { //获取request中的token string token = HttpContext.Current.Request.Headers["Authorization"]; //去掉前面的Bearer if (token != null && token.StartsWith("Bearer")) token = token.Substring("Bearer ".Length).Trim(); try { var json = GetTokenJson(token); TokenInfo info = myJson.Deserialize<TokenInfo>(json); return "Token is true"; } catch (TokenExpiredException) { return "Token has expired"; } catch (SignatureVerificationException) { return "Token has invalid signature"; } } public static string GetTokenJson(string token) { try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); var json = decoder.Decode(token, SecretKey, verify: true); return json; } catch (Exception) { throw; } } } }
使用方法
//生成Token TokenInfo tokenInfo = new TokenInfo(); tokenInfo.Pwd = password; tokenInfo.UserName = tel; string token = TokenHelper.GenToken(tokenInfo); ........ //token验证 string tokenInfo = TokenHelper.DecodeToken(); ........
工具类已将返回的Request的token值提取出,无须传值