From 85985252af713c131a9c87da0a173e24d7122f63 Mon Sep 17 00:00:00 2001 From: Young Date: Tue, 22 Oct 2024 21:50:55 +0800 Subject: [PATCH] optimise token generate and validation --- .../Extensions/AuthenticationSetup.cs | 6 +++-- .../HttpUserContext/UserContext.cs | 24 +++++++++++-------- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/src/Infrastructure/Extensions/AuthenticationSetup.cs b/src/Infrastructure/Extensions/AuthenticationSetup.cs index 1e28d34..ccfa540 100644 --- a/src/Infrastructure/Extensions/AuthenticationSetup.cs +++ b/src/Infrastructure/Extensions/AuthenticationSetup.cs @@ -43,9 +43,11 @@ public static class AuthenticationSetup ValidateAudience = true, ValidAudience = audienceOptions.Audience, ValidateLifetime = true, - ClockSkew = TimeSpan.FromSeconds(300), + ClockSkew = TimeSpan.FromSeconds(0), RequireExpirationTime = true, - RoleClaimType = ClaimTypes.Role + RoleClaimType = ClaimTypes.Role, + LifetimeValidator = (before, expires, token, parameters) => + before < DateTime.UtcNow - parameters.ClockSkew && DateTime.UtcNow < expires + parameters.ClockSkew }; var builder = services.AddAuthentication(options => diff --git a/src/Infrastructure/HttpUserContext/UserContext.cs b/src/Infrastructure/HttpUserContext/UserContext.cs index 3005cb2..0c7a930 100644 --- a/src/Infrastructure/HttpUserContext/UserContext.cs +++ b/src/Infrastructure/HttpUserContext/UserContext.cs @@ -21,7 +21,9 @@ public class UserContext( JsonWebTokenHandler jsonWebTokenHandler) : IUserContext where TId : IEquatable { - private readonly ClaimsPrincipal principal = httpContextAccessor?.HttpContext?.User; + private readonly ClaimsPrincipal principal = + httpContextAccessor.HttpContext?.User ?? + throw new ArgumentNullException(nameof(httpContextAccessor.HttpContext)); private TId? _id; @@ -98,7 +100,7 @@ public class UserContext( duration = jwtContext.Duration; } - var tokenDescriptor = new SecurityTokenDescriptor() + var tokenDescriptor = new SecurityTokenDescriptor { Issuer = jwtContext.Issuer, Audience = jwtContext.Audience, @@ -106,6 +108,7 @@ public class UserContext( NotBefore = DateTime.UtcNow, Expires = DateTime.UtcNow.AddSeconds(duration), SigningCredentials = jwtContext.SigningCredentials, + IssuedAt = DateTime.UtcNow }; var token = jsonWebTokenHandler.CreateToken(tokenDescriptor); token = encryptionService.Encrypt(token); @@ -114,17 +117,12 @@ public class UserContext( public IList? GetClaimsFromUserContext(bool includePermissions = false) { - var claims = new List() + var claims = new List { new(JwtRegisteredClaimNames.UniqueName, Username), new(JwtRegisteredClaimNames.NameId, Id.ToString() ?? string.Empty), new(JwtRegisteredClaimNames.Name, Name), - new(JwtRegisteredClaimNames.Email, Email), - new(JwtRegisteredClaimNames.Iat, - EpochTime.GetIntDate(DateTime.UtcNow).ToString(CultureInfo.InvariantCulture), - ClaimValueTypes.Integer64), - new(JwtRegisteredClaimNames.Exp, - TimeSpan.FromSeconds(jwtContext.Duration).ToString()) + new(JwtRegisteredClaimNames.Email, Email) }; claims.AddRange(RoleIds.Select(rId => new Claim(ClaimConstants.RoleId, rId))); claims.AddRange(RoleNames.Select(rName => new Claim(ClaimTypes.Role, rName))); @@ -138,8 +136,14 @@ public class UserContext( private TId GetIdFromClaims() { + if (_id is not null && !_id.Equals(default)) + { + return _id; + } + var idClaim = principal.Claims.First(c => c.Type == JwtRegisteredClaimNames.NameId); - return (TId)Convert.ChangeType(idClaim.Value, typeof(TId)); + _id = (TId)Convert.ChangeType(idClaim.Value, typeof(TId)); + return _id; } private string GetClaimValue(string claimType)