c#中token怎么用
这篇文章主要介绍了c#中token怎么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
token的存在意义这是我初略了解的token的存在意义
用户使用用户名密码来请求服务器
服务器进行验证用户的信息
服务器通过验证发送给用户一个token
客户端存储token,并在每次请求时附送上这个token值
服务端验证token值,并返回数据
使用方法先安装一个JWT,注意NetFramework的版本
创建一个工具类TokenInfo.cs
usingJWT;usingJWT.Algorithms;usingJWT.Serializers;usingSystem;usingSystem.Collections.Generic;usingSystem.Web;usingSystem.Web.Script.Serialization;namespaceProjectLYG.Common{publicclassTokenInfo{publicTokenInfo(){UserName="j";Pwd="123456";}publicstringUserName{get;set;}publicstringPwd{get;set;}}publicclassTokenHelper{publicstaticstringSecretKey="bqsid123k12s0h2d3uhf493fh02hdd102h9s3h48ff";//这个服务端加密秘钥属于私钥privatestaticJavaScriptSerializermyJson=newJavaScriptSerializer();///<summary>///生成Token///</summary>///<paramname="M"></param>///<returns></returns>publicstaticstringGenToken(TokenInfoM){varpayload=newDictionary<string,dynamic>{{"UserName",M.UserName},//用于存放当前登录人账户信息{"UserPwd",M.Pwd}//用于存放当前登录人登录密码信息};IJwtAlgorithmalgorithm=newHMACSHA256Algorithm();IJsonSerializerserializer=newJsonNetSerializer();IBase64UrlEncoderurlEncoder=newJwtBase64UrlEncoder();IJwtEncoderencoder=newJwtEncoder(algorithm,serializer,urlEncoder);returnencoder.Encode(payload,SecretKey);}///<summary>///验证Token///</summary>///<returns></returns>publicstaticstringDecodeToken(){//获取request中的tokenstringtoken=HttpContext.Current.Request.Headers["Authorization"];//去掉前面的Bearerif(token!=null&&token.StartsWith("Bearer"))token=token.Substring("Bearer".Length).Trim();try{varjson=GetTokenJson(token);TokenInfoinfo=myJson.Deserialize<TokenInfo>(json);return"Tokenistrue";}catch(TokenExpiredException){return"Tokenhasexpired";}catch(SignatureVerificationException){return"Tokenhasinvalidsignature";}}publicstaticstringGetTokenJson(stringtoken){try{IJsonSerializerserializer=newJsonNetSerializer();IDateTimeProviderprovider=newUtcDateTimeProvider();IJwtValidatorvalidator=newJwtValidator(serializer,provider);IBase64UrlEncoderurlEncoder=newJwtBase64UrlEncoder();IJwtDecoderdecoder=newJwtDecoder(serializer,validator,urlEncoder);varjson=decoder.Decode(token,SecretKey,verify:true);returnjson;}catch(Exception){throw;}}}}
使用方法
//生成TokenTokenInfotokenInfo=newTokenInfo();tokenInfo.Pwd=password;tokenInfo.UserName=tel;stringtoken=TokenHelper.GenToken(tokenInfo);........//token验证stringtokenInfo=TokenHelper.DecodeToken();........
工具类已将返回的Request的token值提取出,无须传值
感谢你能够认真阅读完这篇文章,希望小编分享的“c#中token怎么用”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。