码迷,mamicode.com
首页 > 其他好文 > 详细

JWT事例

时间:2020-05-20 21:34:35      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:void   ogr   res   SHA256   lin   时间   ssi   stat   erro   

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
}

JWT事例

标签:void   ogr   res   SHA256   lin   时间   ssi   stat   erro   

原文地址:https://www.cnblogs.com/wugh8726254/p/12926415.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!