Greg Gum
Greg Gum

Reputation: 37909

How to Encrypt JwtSecurityToken

I want to generate a Jwt Token, and then later validate it.

Create token:

 var user = await this._applicationUserProvider.GetCurrentUserAsync();

        var claims = new[]
                                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                    new Claim(JwtRegisteredClaimNames.NameId, user.Id),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.Token.Key));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(this._appSettings.Token.Issuer,
          this._appSettings.Token.Issuer,
          claims,
          expires: DateTime.Now.AddMinutes(this._appSettings.Token.DownloadTokenExpireMin),
          signingCredentials: creds);

Later, I then want to validate this token:

 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.Token.Key));

        TokenValidationParameters validationParameters =
                new TokenValidationParameters
                {
                    ValidIssuer = this._appSettings.Token.Issuer,
                    ValidAudiences = new[] { this._appSettings.Token.Issuer },
                    IssuerSigningKeys = new[] { key }
                };

        // Now validate the token. If the token is not valid for any reason, an exception will be thrown by the method
        SecurityToken validatedToken;
        JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
        var user = handler.ValidateToken(token, validationParameters, out validatedToken);

This is throwing an error: Jwt is not well formed.

In searching on this, I found this: https://github.com/aspnet/Security/issues/1332 which basically says that the Jwt is not encrypted.

However, I have not been able to figure out how to encrypt the token after signing it.

Upvotes: 2

Views: 1649

Answers (2)

Martin Porter
Martin Porter

Reputation: 1

ChiragMS -

I am dealing with the same issue of encrypting/decrypting the jwt token. From my research, this can be achieved using the Authnetication Events. For example using OIDC:

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = "OpenIdConnect";

            }).AddCookie(options =>
            {
                options.Events = new CookieAuthenticationEvents()
                {
                   //commented out for brevity
                };
            })
            .AddOpenIdConnect(options =>
            {
                //commented out for brevity

                options.Events = new OpenIdConnectEvents
                {
                    OnTokenResponseReceived = context =>
                    {
                        var decryptedContent = YourCryptograpy.Decrypt(context.HttpContext);
                        return Task.CompletedTask;
                    },
                };
            }
    );

Upvotes: 0

CodeFuller
CodeFuller

Reputation: 31282

JwtSecurityTokenHandler.ValidateToken() expects token string in compact serialization format. So after building an instance of JwtSecurityToken, you should serialize it into JWT in compact format.

You could do it with JwtSecurityTokenHandler.WriteToken() call:

var token = new JwtSecurityToken(this._appSettings.Token.Issuer,
  this._appSettings.Token.Issuer,
  claims,
  expires: DateTime.Now.AddMinutes(this._appSettings.Token.DownloadTokenExpireMin),
  signingCredentials: creds);

var tokenHandler = new JwtSecurityTokenHandler();
string tokenSerialized = tokenHandler.WriteToken(token);

As result you get a string like

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJTb21lIFVzZXIiLCJuYW1laWQiOiIxMjMiLCJqdGkiOiIzMTQ3YWJmOC05MWYzLTRhZmItYjYyYi03MzZlZDJhNTg3ZjQiLCJleHAiOjE1MjI4MjUwNTYsImlzcyI6IlNvbWUgSXNzdWVyIiwiYXVkIjoiU29tZSBJc3N1ZXIifQ.RD0NntbPWBZUyyayB6SRmNzBPuZ86c30btLbSmhPUmo

that could be successfully validated by JwtSecurityTokenHandler.ValidateToken().

Upvotes: 4

Related Questions