41 lines
1.4 KiB
C#
41 lines
1.4 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace Hutopy.Infrastructure.Utils;
|
|
|
|
public static class JwtTokenHelper
|
|
{
|
|
public static string GenerateJwtToken(string issuer, string audience, string key, string? userId, string? email,
|
|
string? firstname, string? lastname, string? portraitUrl)
|
|
{
|
|
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
|
|
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
|
|
|
|
var claims = new List<Claim>(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.GivenName, firstname),
|
|
new Claim(ClaimTypes.Surname, lastname),
|
|
});
|
|
|
|
if (portraitUrl is not null)
|
|
{
|
|
claims.Add(new Claim("portrait-url", portraitUrl));
|
|
}
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: issuer,
|
|
audience: audience,
|
|
claims: claims,
|
|
expires: DateTime.Now.AddMinutes(30),
|
|
signingCredentials: credentials);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
}
|