Qué Padre Qué Padre - 1 year ago 308
C# Question

How to encrypt JWT security token?

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
. Then I read token string with another

var tokenHandlerDecr = new JwtSecurityTokenHandler();
var tok = tokenHandlerDecr.ReadToken(tokenString);

And token content is not encrypted (I can see json in
variable under debugger). What am I doing wrong? How to encrypt token data?

Answer Source

My understanding is that Microsoft's JWT implementation doesn't currently support encryption (only signing).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download