I need to secure my web-token with signing and encryption. I wrote the next lines of code:
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, owner.Name),
new Claim(ClaimTypes.Role, owner.RoleClaimType),
new Claim("custom claim type", "custom content")
}),
TokenIssuerName = "self",
AppliesToAddress = "http://www.example.com",
Lifetime = new Lifetime(now, now.AddSeconds(60 * 3)),
EncryptingCredentials = new X509EncryptingCredentials(new X509Certificate2(cert)),
SigningCredentials = new X509SigningCredentials(cert1)
};
var token = (JwtSecurityToken)tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
So, I am using some certificates, generated with makecert.exe
. Then I read token string with another JwtSecurityTokenHandler
:
var tokenHandlerDecr = new JwtSecurityTokenHandler();
var tok = tokenHandlerDecr.ReadToken(tokenString);
And token content is not encrypted (I can see json in tok
variable under debugger). What am I doing wrong? How to encrypt token data?
My understanding is that Microsoft's JWT implementation doesn't currently support encryption (only signing).
I know this an old post, but I am adding my answer in case if someone is still searching for the answer.
This issue is addressed in
Microsoft.IdentityModel.Tokens
version 5.1.3. There is an overloaded method available in theCreateJwtSecurityToken
function which accepts the encrypting credentials to encrypt the token.If the receiver does not validate the signature and tries to read JWT as is then the claims are empty. Following is the code snippet:
And here is the code to validate/decrypt the token: