JWT事例

using System;
using JWT;
using JWT.Algorithms;
using System.Collections;
using System.Collections.Generic;
using JWT.Serializers;
namespace JwtTest
{
class Program
{
//Install-Package JWT -Version 2.4.2
private static string secret = "fjxiaowtestadmin";
static void Main(string[] args)
{

string token= SetJwtEncode();
// Console.WriteLine("生成的token:"+ result);
string model = GetJwtDecode(token);
Console.WriteLine("用户信息:" + model);
Console.ReadLine();
}


#region 生成JwtToken
/// <summary>
/// 生成JwtToken
/// </summary>
/// <param name="payload">不敏感的用户数据</param>
/// <returns></returns>
public static string SetJwtEncode()
{

//格式如下
IDateTimeProvider provider = new UtcDateTimeProvider();
var now = provider.GetNow();
var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
//过期时间
var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);

var payload = new Dictionary<string, object>
{
{ "exp", secondsSinceEpoch+3600 }, //3600秒后过期
{ "username","xiaowu" },
{ "password","111111" }
};
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

var token = encoder.Encode(payload, secret);
return token;
}
#endregion


#region 获取实体
/// 根据jwtToken 获取实体
/// </summary>
/// <param name="token">jwtToken</param>
/// <returns></returns>
public static string GetJwtDecode(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);
//token为之前生成的字符串
var userInfo = decoder.DecodeToObject(token, secret, verify: true);
//此处json为IDictionary<string, object> 类型
string username = userInfo["username"].ToString(); //可获取当前用户名
return "用户名是:" + username;

}
catch (TokenExpiredException)
{
Console.WriteLine("Token has expired");
}
catch (SignatureVerificationException)
{
Console.WriteLine("Token has invalid signature");
}
return "Error";
}
}
#endregion
}

posted @ 2020-05-20 21:23  .net&new  阅读(164)  评论(0编辑  收藏  举报