53 lines
1.6 KiB
C#
53 lines
1.6 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace Hutopy.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)
|
|
{
|
|
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));
|
|
}
|
|
|
|
JwtSecurityToken token = new(
|
|
issuer,
|
|
audience,
|
|
claims,
|
|
expires: DateTime.Now.Add(expiresIn),
|
|
signingCredentials: credentials);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
}
|