Skip to content

Instantly share code, notes, and snippets.

@Chriz76
Last active March 9, 2021 12:27
Show Gist options
  • Save Chriz76/4adca6d3df876d75ecd4ba88094063c6 to your computer and use it in GitHub Desktop.
Save Chriz76/4adca6d3df876d75ecd4ba88094063c6 to your computer and use it in GitHub Desktop.
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
namespace AuthService
{
public class JwtGenerator
{
readonly RsaSecurityKey _key;
public JwtGenerator(string signingKey)
{
RSA privateRSA = RSA.Create();
privateRSA.ImportRSAPrivateKey(Convert.FromBase64String(signingKey), out _);
_key = new RsaSecurityKey(privateRSA);
}
public string CreateUserAuthToken(string userId)
{
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Audience = "myApi",
Issuer = "AuthService",
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Sid, userId.ToString())
}),
Expires = DateTime.UtcNow.AddMinutes(60),
SigningCredentials = new SigningCredentials(_key, SecurityAlgorithms.RsaSha256)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment