optimise token generate and validation

master
Young 7 months ago
parent 4cae00bd86
commit 85985252af

@ -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 =>

@ -21,7 +21,9 @@ public class UserContext<TId>(
JsonWebTokenHandler jsonWebTokenHandler)
: 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;
@ -98,7 +100,7 @@ public class UserContext<TId>(
duration = jwtContext.Duration;
}
var tokenDescriptor = new SecurityTokenDescriptor()
var tokenDescriptor = new SecurityTokenDescriptor
{
Issuer = jwtContext.Issuer,
Audience = jwtContext.Audience,
@ -106,6 +108,7 @@ public class UserContext<TId>(
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<TId>(
public IList<Claim>? GetClaimsFromUserContext(bool includePermissions = false)
{
var claims = new List<Claim>()
var claims = new List<Claim>
{
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<TId>(
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)

Loading…
Cancel
Save