I am working on .Net Core Web API, in which we are using Jwt Token for authorizing web requests. Below is the code to generate token and configure it in the startup.
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Security:Key"])),
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5)
};
});
Generate Token :
private string GenerateToken(string username)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, username),
new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()),
new Claim(ClaimTypes.Role, "PB"),
new Claim(ClaimTypes.Version, _configuration["Version"]),
};
var token = new JwtSecurityToken(
new JwtHeader(new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Security:Key"])),
SecurityAlgorithms.HmacSha256)),
new JwtPayload(claims));
return new JwtSecurityTokenHandler().WriteToken(token);
}
This is working as expected. Recently we received a suggestion that instead of using _configuration["Security:Key"] hardcoded secret key to sign the token, make use of Data Protection API. After going through the documentation, I have the following questions:
- How to combine JWT Token Signing with Data Protection API?
- Do I have to use keys from DPAPI to sign the token or Use DPAPI's protect and unprotect method to do send the encrypted token in response?
- I am not able to find any way to encrypt the token using DPAPI. Is it even possible?
- Is it good practise to extract the master key/ or any key from DPAPI to do the token signing?
Any Suggestions?
Our goal is to get rid of the configuration based secret key and make use of DPAPI.
Edit:
As mentioned by @jps in the comment section, in this case, we have to store the singing the key using DPAPI.
Updated Question:
How do I achieve the same? Any code samples would be helpful.