2025-06-16 17:24:23 +08:00

107 lines
3.6 KiB
C#

using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
namespace Syc.Authorize.JwtBearer
{
[Dependency(Microsoft.Extensions.DependencyInjection.ServiceLifetime.Transient)]
public class JwtTokenService : IJwtTokenService
{
private JwtBearerAuthenticationOptions JwtSetting { get; set; }
private JwtSecurityTokenHandler JwtSecurityTokenHandler { get; set; }
public JwtTokenService(IOptions<JwtBearerAuthenticationOptions> options)
{
JwtSetting = options.Value;
JwtSecurityTokenHandler = new JwtSecurityTokenHandler();
}
/// <summary>
/// 生成 token
/// </summary>
/// <param name="obj"></param>
/// <param name="jwtSetting"></param>
/// <returns></returns>
public string GenerateToken(object obj, JwtBearerAuthenticationOptions jwtSetting = null)
{
jwtSetting = jwtSetting ?? JwtSetting;
var dics = GetPropertieValues(obj);
//组装claims
var claims = dics.Where(e => e.Value is not null).Select(x => new Claim(x.Key, x.Value?.ToString())).ToList();
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.SecurityKey));
var credentials = new SigningCredentials(key, string.IsNullOrWhiteSpace(jwtSetting.Algorithms) ? SecurityAlgorithms.HmacSha256 : jwtSetting.Algorithms);
var jwtSecurityToken = new JwtSecurityToken(jwtSetting.Issuer, jwtSetting.Audience, claims, null, DateTime.Now.AddMinutes(jwtSetting.ExpiredTime), credentials);
return JwtSecurityTokenHandler.WriteToken(jwtSecurityToken);
}
/// <summary>
/// 获取对象属性键值对
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public IDictionary<string, object> GetPropertieValues(object obj)
{
var t = obj.GetType();
var props = t.GetProperties();
IDictionary<string, object> dics = new Dictionary<string, object>();
if (props is not null && props.Any())
foreach (var prop in props)
{
dics.Add(prop.Name, prop.GetValue(obj));
}
return dics;
}
/// <summary>
/// get claims by token
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public IEnumerable<Claim> GetClaims(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
return tokenHandler.ReadJwtToken(token)?.Claims;
}
/// <summary>
/// 手动验证token
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public bool ValidateToken(string token, TokenValidationParameters tokenValidationParameters = null)
{
tokenValidationParameters = tokenValidationParameters ?? JwtSetting.TokenValidationParameters;
SecurityToken validatedToken = null;
try
{
JwtSecurityTokenHandler.ValidateToken(token, tokenValidationParameters, out validatedToken);
}
catch (SecurityTokenException stexp)
{
return false;
}
catch (Exception e)
{
return false;
}
return validatedToken != null;
}
}
}