这篇文章主要介绍了c#中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 = "bqsid123k12s0h2d3uhf493fh02hdd102h9s3h48ff";//这个服务端加密秘钥 属于私钥 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值提取出,无须传值
感谢你能够认真阅读完这篇文章,希望小编分享的“c#中token怎么用”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。