DEV Community

Verónica Guamán
Verónica Guamán

Posted on

1

Cambiar el valor NBF del JWT en ASP.NET MVC API - C#

NBF en JWT significa Not Before

  • Claim Name: "nbf"
  • Claim Description: Not Before

Obtiene o establece la hora no anterior para el token de seguridad. Este valor debe estar en UTC.
Es decir nbf: Define el tiempo antes del cual el JWT NO DEBE ser aceptado para su procesamiento.

Si por algún motivo tenemos o debemos cambiar el valor de NFB podemos hacerlo de la siguiente forma.

En la configuración para obtener nuestro token vamos a tener algo parecido a esto:

private string generateJwtToken(User user)
        {
            // generate token that is valid for 7 days
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()) }),
                NotBefore = DateTime.UtcNow.AddMinutes(5),
                Expires = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
Enter fullscreen mode Exit fullscreen mode

dentro de esta configuración la línea antes de especificar la expiración vamos a colocar la siguiente línea.
NotBefore = DateTime.UtcNow.AddMinutes(5)
Agregamos el tiempo en el que queremos que esté disponible nuestro token, en este caso de ejemplo le estoy agregando 5 minutos a la hora y fecha actual.

Y ya podemos observar los cambios generando el token y probándolo en https://jwt.io/

Eso es todo por hoy, espero que te sirvan de mucho estos recursos.

Puedes seguirme en Twitter, Instagram o Facebook para más contenido técnico, consejos y más.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay