作者:薛佩璇-_585 | 来源:互联网 | 2023-09-23 19:23
这篇文章主要介绍了c#中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();
///
/// 生成Token
///
///
///
public static string GenToken(TokenInfo M)
{
var payload = new Dictionary
{
{"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);
}
///
/// 验证Token
///
///
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(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怎么用”这篇文章对大家有帮助,同时也希望大家多多支持编程笔记,关注编程笔记行业资讯频道,更多相关知识等着你来学习!