Last active
March 9, 2021 12:27
-
-
Save Chriz76/4adca6d3df876d75ecd4ba88094063c6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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