We are using the JWT Nuget to create and validate token. Here is the code that we use to create token
private string CreateAccessToken(Dictionary<string, object> payload)
{
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
var token = encoder.Encode(payload, GetJWTKey());
return token;
}
My understanding is, this doesn't encrypt the token as I was able to parse the token by visting jwt.io and was able to read the contents. I would like to encrypt the token such that it should not be parsed. I wasn't able to find any method in JWT Nuget through which I can encrypt the token.
So how do I sign and encrypt the token using JWT Nuget?
Edit:
I understand that JWT doesn't require any encryption as only the authenticated user will be able to read the token which means, I am reading about my own contents and also, the actual communication will be over secured layer. So actually there is no need to encrypt the token yet, my requirement is the token shouldn't be human readable
Your understanding is correct but you are missing an important feature of JWT: encrypting the token is not a purpose of JWT.
The secret used by the algorithm is used to sign the token and not for encrypting it, for more information take a look to the RFC 7515.
As suggested in the comments below there is also the RFC 7516, Json Web Encryption (JWE).
For using JWE inside a C# application you have to use the System.IdentityModel.Tokens.Jwt package, and then something like:
var handler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Audience = "audience",
//other property
EncryptingCredentials = new X509EncryptingCredentials(new X509Certificate2("path/to/public/key"))
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With