CSharp-Single-EFCore/Bunny.Common/Utils/Jwt/JwtUtil.cs

88 lines
2.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
namespace Bunny.Common.Utils.Jwt;
public static partial class JwtUtil
{
/// <summary>
/// 默认发布者
/// </summary>
private const string JwtKey = "这你放的是你的秘钥必须要256位以上否则会报错";
/// <summary>
/// 默认发布者
/// </summary>
private const string Issuer = "Bunny-Issuer";
/// <summary>
/// 默认接受者
/// </summary>
private const string Audience = "Bunny-Audience";
/// <summary>
/// 默认有效时间,按天计算
/// </summary>
private const int Day = 7;
/// <summary>
/// 判断是否过期
/// </summary>
/// <param name="jwtToken">token</param>
/// <returns>过期true未过期false</returns>
public static bool IsJwtExpired(string? jwtToken)
{
var tokenHandler = new JwtSecurityTokenHandler();
// Token无效直接返回过期
if (tokenHandler.ReadToken(jwtToken) is not JwtSecurityToken jwtTokenObj) return true;
// 判断是否过期
return DateTime.UtcNow > jwtTokenObj.ValidTo;
}
/// <summary>
/// 生成 SigningCredentials
/// </summary>
private static SigningCredentials Credentials(string jwtKey)
{
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));
return new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);
}
/// <summary>
/// 将字典转为实体类
/// </summary>
/// <param name="dictionary">字典</param>
/// <returns>所对应的实体类</returns>
// public static T? ConvertDictionaryToObject(Dictionary<string, object> dictionary)
// {
// var json = JsonConvert.SerializeObject(dictionary);
// // 将JSON转为对象
// return JsonConvert.DeserializeObject<T>(json);
// }
public static T? ConvertDictionaryToObject<T>(Dictionary<string, object> dictionary)
{
var json = JsonConvert.SerializeObject(dictionary);
// 将JSON转为对象
return JsonConvert.DeserializeObject<T>(json);
}
/// <summary>
/// 将对象转为Claim
/// </summary>
/// <param name="object">要转换的对象</param>
/// <returns>Claim</returns>
public static IEnumerable<Claim> CreateClaim<T>(T @object)
{
// 将对象序列化成JSON
var json = JsonConvert.SerializeObject(@object);
// 将JSON复制给Claim
return ParseJsonToClaimEnumerable(json);
}
}