c#中token的使用方法实例
程序员文章站
2022-06-03 23:50:22
目录token的存在意义使用方法token的存在意义这是我初略了解的token的存在意义用户使用用户名密码来请求服务器服务器进行验证用户的信息服务器通过验证发送给用户一个token客户端存储token...
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值提取出,无须传值
到此这篇关于c#中token的使用方法实例的文章就介绍到这了,更多相关c# token内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!