optimise codes

master
Young 7 months ago
parent cbd0eaa353
commit 1ddacab128

@ -10,7 +10,7 @@ public static class TokenContextSetup
public static IServiceCollection AddDefaultTokenContext(this IServiceCollection services) public static IServiceCollection AddDefaultTokenContext(this IServiceCollection services)
{ {
ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(services);
services.TryAddSingleton<JwtSecurityTokenHandler>(); services.TryAddSingleton<JsonWebTokenHandler>();
services.TryAddSingleton<DefaultTokenHandler>(); services.TryAddSingleton<DefaultTokenHandler>();
return services; return services;
} }

@ -11,7 +11,8 @@ global using System.Reflection;
global using System.Text; global using System.Text;
global using System.Text.Json; global using System.Text.Json;
global using System.Threading; global using System.Threading;
global using System.IdentityModel.Tokens.Jwt;
global using Infrastructure.Security; global using Infrastructure.Security;
global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.DependencyInjection.Extensions; global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Microsoft.IdentityModel.JsonWebTokens;
global using Microsoft.IdentityModel.Tokens;

@ -3,7 +3,6 @@ using System.Security.Claims;
using Infrastructure.Utils; using Infrastructure.Utils;
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
namespace Infrastructure.HttpUserContext; namespace Infrastructure.HttpUserContext;
@ -13,13 +12,13 @@ namespace Infrastructure.HttpUserContext;
/// <param name="httpContextAccessor"></param> /// <param name="httpContextAccessor"></param>
/// <param name="jwtContext"></param> /// <param name="jwtContext"></param>
/// <param name="encryptionService"></param> /// <param name="encryptionService"></param>
/// <param name="jwtSecurityTokenHandler"></param> /// <param name="jsonWebTokenHandler"></param>
/// <typeparam name="TId"></typeparam> /// <typeparam name="TId"></typeparam>
public class UserContext<TId>( public class UserContext<TId>(
IHttpContextAccessor httpContextAccessor, IHttpContextAccessor httpContextAccessor,
JwtContext jwtContext, JwtContext jwtContext,
IEncryptionService encryptionService, IEncryptionService encryptionService,
JwtSecurityTokenHandler jwtSecurityTokenHandler) JsonWebTokenHandler jsonWebTokenHandler)
: IUserContext<TId> where TId : IEquatable<TId> : IUserContext<TId> where TId : IEquatable<TId>
{ {
private readonly ClaimsPrincipal principal = httpContextAccessor?.HttpContext?.User; private readonly ClaimsPrincipal principal = httpContextAccessor?.HttpContext?.User;
@ -48,13 +47,13 @@ public class UserContext<TId>(
public string Username public string Username
{ {
get => _username ??= principal.Claims.First(c => c.Type == JwtRegisteredClaimNames.UniqueName).Value; get => _username ??= GetClaimValue(JwtRegisteredClaimNames.UniqueName);
set => _username = value; set => _username = value;
} }
public string Name public string Name
{ {
get => _name ??= principal.Claims.First(c => c.Type == JwtRegisteredClaimNames.Name).Value; get => _name ??= GetClaimValue(JwtRegisteredClaimNames.Name);
set => _name = value; set => _name = value;
} }
@ -101,14 +100,16 @@ public class UserContext<TId>(
duration = jwtContext.Duration; duration = jwtContext.Duration;
} }
var securityToken = new JwtSecurityToken( var tokenDescriptor = new SecurityTokenDescriptor()
issuer: jwtContext.Issuer, {
audience: jwtContext.Audience, Issuer = jwtContext.Issuer,
claims: claims, Audience = jwtContext.Audience,
notBefore: DateTime.Now, Claims = claims?.ToDictionary(c => c.Type, c => (object)c.Value),
expires: DateTime.Now.AddSeconds(jwtContext.Duration), NotBefore = DateTime.Now,
signingCredentials: jwtContext.SigningCredentials); Expires = DateTime.Now.AddSeconds(duration.Value),
var token = jwtSecurityTokenHandler.WriteToken(securityToken); SigningCredentials = jwtContext.SigningCredentials,
};
var token = jsonWebTokenHandler.CreateToken(tokenDescriptor);
token = encryptionService.Encrypt(token); token = encryptionService.Encrypt(token);
return new JwtTokenInfo(token, duration.Value, schemeName); return new JwtTokenInfo(token, duration.Value, schemeName);
} }
@ -142,4 +143,14 @@ public class UserContext<TId>(
var idClaim = principal.Claims.First(c => c.Type == JwtRegisteredClaimNames.NameId); var idClaim = principal.Claims.First(c => c.Type == JwtRegisteredClaimNames.NameId);
return (TId)Convert.ChangeType(idClaim.Value, typeof(TId)); return (TId)Convert.ChangeType(idClaim.Value, typeof(TId));
} }
private string GetClaimValue(string claimType)
{
return principal.Claims.First(c => c.Type == claimType).Value;
}
private string[] GetClaimValues(string claimType)
{
return principal.Claims.Where(c => c.Type == claimType).Select(c => c.Value).ToArray();
}
} }

@ -1,19 +1,17 @@
using Microsoft.IdentityModel.Tokens;
namespace Infrastructure.Security; namespace Infrastructure.Security;
/// <summary> /// <summary>
/// 自定义token解密 /// 自定义token解密
/// </summary> /// </summary>
/// <param name="encryptionService"></param> /// <param name="encryptionService"></param>
/// <param name="jwtSecurityTokenHandler"></param> /// <param name="jwtTokenHandler"></param>
public class DefaultTokenHandler(IEncryptionService encryptionService, JwtSecurityTokenHandler jwtSecurityTokenHandler) public class DefaultTokenHandler(IEncryptionService encryptionService, JsonWebTokenHandler jwtTokenHandler)
: TokenHandler : TokenHandler
{ {
public override Task<TokenValidationResult> ValidateTokenAsync(string token, public override Task<TokenValidationResult> ValidateTokenAsync(string token,
TokenValidationParameters validationParameters) TokenValidationParameters validationParameters)
{ {
var decodeToken = encryptionService.Decrypt(token); var decodeToken = encryptionService.Decrypt(token);
return jwtSecurityTokenHandler.ValidateTokenAsync(decodeToken, validationParameters); return jwtTokenHandler.ValidateTokenAsync(decodeToken, validationParameters);
} }
} }

@ -1,5 +1,3 @@
using Microsoft.IdentityModel.Tokens;
namespace Infrastructure.Security; namespace Infrastructure.Security;
/// <summary> /// <summary>

Loading…
Cancel
Save