下载jwt:
具体代码如下:
using JWT;
using JWT.Algorithms;
using JWT.Exceptions;
using JWT.Serializers;
using System;
using System.Collections.Generic;
namespace Test_jwt
{
public class JWTHelper
{
static IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//HMACSHA256加密
static IJsonSerializer serializer = new JsonNetSerializer();//序列化和反序列
static IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//Base64编解码
static IDateTimeProvider provider = new UtcDateTimeProvider();//UTC时间获取
#region /生成JWT
public static string GetJWT(string secret, Dictionary<string, object> payload)
{
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
return encoder.Encode(payload, secret);
}
#endregion
#region /验证JWT
public static bool ValidateJwt(string secret, string token, out string payload, out string message)
{
bool isValidted = false;
payload = "";
try
{
IJwtValidator validator = new JwtValidator(serializer, provider);//用于验证JWT的类
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);//用于解析JWT的类
payload = decoder.Decode(token, secret, verify: true);//verify:true表示解析JWT时进行验证,该方法会自动调用validator的Validate()方法,不满足验证会抛出异常,因此我们不用写验证的方法
isValidted = true;
message = "验证成功";
}
catch (TokenExpiredException)//如果当前时间大于负载中的过期时间(负荷中的exp),引发Token过期异常
{
message = "Token已经过期了!";
}
catch (SignatureVerificationException)//如果签名不匹配,引发签名验证异常
{
message = "Token签名不正确!";
}
return isValidted;
}
#endregion
}
class Program
{
static void Main(string[] args)
{
//服务端的秘钥,一般放在配置文件中
const string secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
//负荷(payload)
var payload = new Dictionary<string, object>
{
{ "claim1", 0 },
{ "testStr", "hello" },
{"testObj" ,new { name="111"} },
{ "exp", DateTimeOffset.UtcNow.AddSeconds(2).ToUnixTimeSeconds() }
};
Console.WriteLine("生成JWT--------------------------------------------------------------");
Console.WriteLine();
string token = JWTHelper.GetJWT(secret, payload);
Console.WriteLine($"生成的JWT是:{token}");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("校验JWT--------------------------------------------------------------");
Console.WriteLine();
string message;//解析的消息
string curPayload;//解析获取的负载
if (JWTHelper.ValidateJwt(secret, token, out curPayload, out message))
{
Console.WriteLine($"解析获取的负载是:{curPayload}");
}
Console.WriteLine(message);
Console.ReadKey();
}
}
}
输出结果: