Skip to content

Instantly share code, notes, and snippets.

@bramburn
Created October 3, 2020 19:29
Show Gist options
  • Save bramburn/53abcb6771ed3b1a2a68fe7e9f3dbd4d to your computer and use it in GitHub Desktop.
Save bramburn/53abcb6771ed3b1a2a68fe7e9f3dbd4d to your computer and use it in GitHub Desktop.
public class JwtService
{
private string _secret;
private int _expDate;
private IConfiguration _config;
public JwtService(IConfiguration config)
{
_secret = config.GetSection("JwtConfig").GetSection("secret").Value;
_config = config;
_expDate = int.Parse(config.GetSection("JwtConfig").GetSection("expirationInMinutes").Value);
}
public static RSAParameters FromXmlString(string xmlString)
{
var parameters = new RSAParameters();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
if (xmlDoc.DocumentElement.Name.Equals("RSAKeyValue"))
{
foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
{
switch (node.Name)
{
case "Modulus":
parameters.Modulus = Convert.FromBase64String(node.InnerText);
break;
case "Exponent":
parameters.Exponent = Convert.FromBase64String(node.InnerText);
break;
case "P":
parameters.P = Convert.FromBase64String(node.InnerText);
break;
case "Q":
parameters.Q = Convert.FromBase64String(node.InnerText);
break;
case "DP":
parameters.DP = Convert.FromBase64String(node.InnerText);
break;
case "DQ":
parameters.DQ = Convert.FromBase64String(node.InnerText);
break;
case "InverseQ":
parameters.InverseQ = Convert.FromBase64String(node.InnerText);
break;
case "D":
parameters.D = Convert.FromBase64String(node.InnerText);
break;
}
}
}
else
{
throw new Exception("Invalid XML RSA key.");
}
//then use rsa.Import
return parameters;
}
public RsaSecurityKey getSecurityKeyFromParam(string location)
{
var publicRsa = RSA.Create();
var publicXMLContent = File.ReadAllText(location);
publicRsa.ImportParameters(FromXmlString(publicXMLContent));
return new RsaSecurityKey(publicRsa);
}
private SigningCredentials ProcessPrivateKey(string location)
{
return new SigningCredentials(getSecurityKeyFromParam(location), SecurityAlgorithms.RsaSha256);
}
public string GenerateToken(string email)
{
SigningCredentials pkey = ProcessPrivateKey(_config.GetSection("JwtConfig").GetSection("privateXml").Value);
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Email, email)
}),
// Audience = "localhost",
Issuer = _config.GetSection("JwtConfig").GetSection("Issuer").Value,
Expires = DateTime.UtcNow.AddMinutes(_expDate),
SigningCredentials = pkey
};
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