67 lines
2.1 KiB
C#
67 lines
2.1 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace Socialize.Infrastructure.Security;
|
|
|
|
public static class JwtTokenHelper
|
|
{
|
|
public static string GenerateJwtToken(
|
|
TimeSpan expiresIn,
|
|
string issuer,
|
|
string audience,
|
|
string key,
|
|
string userId,
|
|
string email,
|
|
string? alias,
|
|
string firstname,
|
|
string lastname,
|
|
string? portraitUrl,
|
|
IEnumerable<string> roles,
|
|
IEnumerable<Claim> additionalClaims)
|
|
{
|
|
SymmetricSecurityKey securityKey = new(Encoding.UTF8.GetBytes(key));
|
|
SigningCredentials credentials = new(securityKey, SecurityAlgorithms.HmacSha256);
|
|
|
|
List<Claim> claims = new([
|
|
new Claim(JwtRegisteredClaimNames.Sub, userId),
|
|
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
|
new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Email, email),
|
|
new Claim(ClaimTypes.Name, email), new Claim(ClaimTypes.GivenName, firstname),
|
|
new Claim(ClaimTypes.Surname, lastname)
|
|
]);
|
|
|
|
if (alias is not null)
|
|
{
|
|
claims.Add(new Claim(KnownClaims.Alias, alias));
|
|
}
|
|
|
|
if (portraitUrl is not null)
|
|
{
|
|
claims.Add(new Claim(KnownClaims.PortraitUrl, portraitUrl));
|
|
}
|
|
|
|
foreach (string role in roles.Distinct(StringComparer.Ordinal))
|
|
{
|
|
claims.Add(new Claim(ClaimTypes.Role, role));
|
|
}
|
|
|
|
foreach (Claim claim in additionalClaims
|
|
.Where(claim => !string.IsNullOrWhiteSpace(claim.Type) && !string.IsNullOrWhiteSpace(claim.Value))
|
|
.DistinctBy(claim => $"{claim.Type}:{claim.Value}"))
|
|
{
|
|
claims.Add(claim);
|
|
}
|
|
|
|
JwtSecurityToken token = new(
|
|
issuer,
|
|
audience,
|
|
claims,
|
|
expires: DateTime.Now.Add(expiresIn),
|
|
signingCredentials: credentials);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
}
|