这是我初六级报考时间略了解的token的存在意义
用户使用用户名密码来请求服务器服务器进行验证用户的信息服务器通过验证发送给用户一个token客户端存储token,并在每次请求时附送上这个token值服务端验证token值,并返回数据先安装一个jwt,注意netframework的版本
创建一个工具类tokeninfo.cs
using jwt;using jwt.algorithms;using jwt.rializers;using system;using system.collections.generic;using system.web;using system.web.script.rialization;namespace projectlyg.common{ public class tokeninfo { public tokeninfo() { urname = "j"; pwd = "123456"; } public strin说三道四的近义词g urname { get; t; } public string pwd { get; t; } } public class tokenhelper { public static string cretkey = "bqsid123k12s0h1d3uhf493fh02hdd102h9s3h38ff";//这个服务端加密秘钥 属于私钥 private static javascriptrializer myjson = new javascriptrializer(); /// <summary> /// 生成token /// </summary> /// <param name="m"></param> /// <returns></returns> public static string gentoken(tokeninfo m) { var payload = new dictionary<string, dynamic> { {"urname", m.urname},//用于存放当前登录人账户信息 {"urpwd", m.pwd}//用于存放当前登录人登录密码信息 }; ijwtalgorithm algorithm = new hmacsha256algorithm(); ijsonrializer rializer = new jsonnetrializer(); iba64urlencoder urlencoder = new j春风得意出自wtba64urlencoder(); ijwtencoder encoder = new jwtencoder(algorithm, rializer, urlencoder); return encoder.encode(payload, cretkey); } /// <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.derialize<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 { ijsonrializer rializer = new jsonnetrializer(); idatetimeprovider provider = new utcdatetimeprovider(); ijwtvalidator validator = new jwtvalidator(rializer, provider); iba64urlencoder urlencoder = new jwtba64urlencoder(); ijwtdecoder decoder = new jwtdecoder(rializer, validator, urlencoder); var json = decoder.decode(token, cretkey, verify: true); return json; } 岳母的乳房 catch (exception) { throw; } } }}
使用方法
//生成token tokeninfo tokeninfo = new tokeninfo(); tokeninfo.pwd = password; tokeninfo.urname = tel; string token = tokenhelper.gentoken(tokeninfo); ........ //token验证 string tokeninfo = tokenhelper.decodetoken(); ........
工具类已将返回的request的token值提取出,无须传值
到此这篇关于c#中token的使用方法实例的文2014河南高考作文题目章就介绍到这了,更多相关c# token内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!
本文发布于:2023-04-05 00:37:51,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/ae7e63e4496193502fe24b360b82878d.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:c#中token的使用方法实例.doc
本文 PDF 下载地址:c#中token的使用方法实例.pdf
留言与评论(共有 0 条评论) |