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