How to remove nbf claim

Viewed 2634

have been looking an answer for this from everywhere, but can't seem to find one that applies to me. The thing is i'm trying to construct a JWT token with ASP.NET in c#. The problem i'm running in to is that somewhere it adds a "nbf" claim automatically to my claims and i can't seem to figure out how to remove it as the API host doesn't allow it in the token. Here's a code snipped of what creates the tokens:

               var plainTextSecurityKey = "key";
            var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(plainTextSecurityKey));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(signingKey,
                Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);


            var claimsIdentity = new ClaimsIdentity(new List<Claim>()
            {
                new Claim("iss", "smthing"),
                new Claim("sub", "smthing"),
                new Claim("iat", ToUnixTime(issued).ToString()),
                new Claim("exp",ToUnixTime(expire).ToString()),
                new Claim("aud", JsonConvert.SerializeObject(new[] { "ohlc" }).ToString())
            });

 claimsIdentity.TryRemoveClaim(claimsIdentity.FindFirst("nbf"));


            var securityTokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
            {
                Subject = claimsIdentity,
                SigningCredentials = signingCredentials,
            };


            securityTokenDescriptor.NotBefore = null;

            var tokenHandler = new JwtSecurityTokenHandler();
            var plainToken = tokenHandler.CreateToken(securityTokenDescriptor);
            var signedAndEncodedToken = tokenHandler.WriteToken(plainToken);

I try to remove the nbf after forming the claimsIdentity, but it appears that it isn't added there.

2 Answers

You are trying to get at it too early, the "nbf" claim is being added when you do this:

var plainToken = tokenHandler.CreateToken(securityTokenDescriptor);

After you create plainToken, you can remove claims you don't want on it, like this:

var tokenHandler = new JwtSecurityTokenHandler();
var plainToken = tokenHandler.CreateToken(securityTokenDescriptor);
plainToken.Payload.Remove("nbf");
var signedAndEncodedToken = tokenHandler.WriteToken(plainToken);
Related