optimise token generate and validation

master
Young 7 months ago
parent 4cae00bd86
commit 85985252af

@ -43,9 +43,11 @@ public static class AuthenticationSetup
ValidateAudience = true, ValidateAudience = true,
ValidAudience = audienceOptions.Audience, ValidAudience = audienceOptions.Audience,
ValidateLifetime = true, ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(300), ClockSkew = TimeSpan.FromSeconds(0),
RequireExpirationTime = true, 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 => var builder = services.AddAuthentication(options =>

@ -21,7 +21,9 @@ public class UserContext<TId>(
JsonWebTokenHandler jsonWebTokenHandler) 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 ??
throw new ArgumentNullException(nameof(httpContextAccessor.HttpContext));
private TId? _id; private TId? _id;
@ -98,7 +100,7 @@ public class UserContext<TId>(
duration = jwtContext.Duration; duration = jwtContext.Duration;
} }
var tokenDescriptor = new SecurityTokenDescriptor() var tokenDescriptor = new SecurityTokenDescriptor
{ {
Issuer = jwtContext.Issuer, Issuer = jwtContext.Issuer,
Audience = jwtContext.Audience, Audience = jwtContext.Audience,
@ -106,6 +108,7 @@ public class UserContext<TId>(
NotBefore = DateTime.UtcNow, NotBefore = DateTime.UtcNow,
Expires = DateTime.UtcNow.AddSeconds(duration), Expires = DateTime.UtcNow.AddSeconds(duration),
SigningCredentials = jwtContext.SigningCredentials, SigningCredentials = jwtContext.SigningCredentials,
IssuedAt = DateTime.UtcNow
}; };
var token = jsonWebTokenHandler.CreateToken(tokenDescriptor); var token = jsonWebTokenHandler.CreateToken(tokenDescriptor);
token = encryptionService.Encrypt(token); token = encryptionService.Encrypt(token);
@ -114,17 +117,12 @@ public class UserContext<TId>(
public IList<Claim>? GetClaimsFromUserContext(bool includePermissions = false) public IList<Claim>? GetClaimsFromUserContext(bool includePermissions = false)
{ {
var claims = new List<Claim>() var claims = new List<Claim>
{ {
new(JwtRegisteredClaimNames.UniqueName, Username), new(JwtRegisteredClaimNames.UniqueName, Username),
new(JwtRegisteredClaimNames.NameId, Id.ToString() ?? string.Empty), new(JwtRegisteredClaimNames.NameId, Id.ToString() ?? string.Empty),
new(JwtRegisteredClaimNames.Name, Name), new(JwtRegisteredClaimNames.Name, Name),
new(JwtRegisteredClaimNames.Email, Email), new(JwtRegisteredClaimNames.Email, Email)
new(JwtRegisteredClaimNames.Iat,
EpochTime.GetIntDate(DateTime.UtcNow).ToString(CultureInfo.InvariantCulture),
ClaimValueTypes.Integer64),
new(JwtRegisteredClaimNames.Exp,
TimeSpan.FromSeconds(jwtContext.Duration).ToString())
}; };
claims.AddRange(RoleIds.Select(rId => new Claim(ClaimConstants.RoleId, rId))); claims.AddRange(RoleIds.Select(rId => new Claim(ClaimConstants.RoleId, rId)));
claims.AddRange(RoleNames.Select(rName => new Claim(ClaimTypes.Role, rName))); claims.AddRange(RoleNames.Select(rName => new Claim(ClaimTypes.Role, rName)));
@ -138,8 +136,14 @@ public class UserContext<TId>(
private TId GetIdFromClaims() private TId GetIdFromClaims()
{ {
if (_id is not null && !_id.Equals(default))
{
return _id;
}
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)); _id = (TId)Convert.ChangeType(idClaim.Value, typeof(TId));
return _id;
} }
private string GetClaimValue(string claimType) private string GetClaimValue(string claimType)

Loading…
Cancel
Save