Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT token expired but it doesnt have expiration time

Tags:

go

I'm working in a simple login with golang i have a route that generates a token jwt with library golang-jwt but when i try to verify the token in a middleware, yes it is a valid token but it keep telling me that is expired, i don't know why

this is my code for generate the token:

func GenerateToken(user models.User) (string, error) {
    tokenBuilder := jwt.NewWithClaims(jwt.SigningMethodHS256 , jwt.MapClaims{
        "user":user.Email,
        "nombre":user.Nombre,
        "apellido":user.Apellido,
        "edad":fmt.Sprint(user.Edad),
        "genero":user.Genero,
        "rol":user.Rol,
    })

    tokenBuilder.Claims.(jwt.MapClaims)["exp"] = nil

    tokenString, err := tokenBuilder.SignedString([]byte(os.Getenv("SECRET")))

    return tokenString,err
    
}

tokenBuilder.Claims.(jwt.MapClaims)["exp"] = nil it was what i think solve the problem. but didn't work

And my middleware is this

type CustomClaims struct {
    jwt.StandardClaims
}

func JWTMiddleware() fiber.Handler {
    return func(c *fiber.Ctx) error {
        authHeader := c.Get("Authorization")
        if authHeader == "" {
            return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
                "message": "No Auth token",
            })
        }

        tokenString := authHeader[7:] //"Bearer "

        token , err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
            return []byte(os.Getenv("SECRET")), nil
        })

        if err != nil {
            return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
                "message": "Invalid token",
            })
        }

        //Check if is expired
        claims, ok := token.Claims.(*CustomClaims)
        if !ok || !token.Valid {
            return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
                "message": "Invalid or expired",
            })
        }

        // Check token expiration time
        if claims.ExpiresAt < time.Now().Unix() {
            return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
                "message": "Expired token",
            })
        }

        return c.Next()
    }
}

I don't really know if my generated token is right or my middleware is right, in this middleware i try to catch tokens even if this doesn't have expiration time, I'm starting in golang, i investigated but im out, this token work with the middleware created by library but i want mines for different purposes. Thank you and good day i hope i have been clear

I try tokenBuilder.Claims.(jwt.MapClaims)["exp"] = nil and in my tokenGeneration make a new claim like this exp:0

like image 925
Hey L1nk Avatar asked Oct 14 '25 08:10

Hey L1nk


1 Answers

If you don't set exp then StandardClaims.ExpiresAt will be it's default value (int64 so 0) and, as such, claims.ExpiresAt < time.Now().Unix() will be true (time.Now().Unix() will be greater than 0!). If you really want to do this then add a check for 0 e.g.

if claims.ExpiresAt != 0 && claims.ExpiresAt < time.Now().Unix() {

It's worth noting that ParseWithClaims verifies exp (so you don't really need to!). Note that it will call Valid so "if any of the above claims are not in the token, it will still be considered a valid claim.".

A better option would be to set a valid expiry...

As a further note creating a Minimal, Reproducible, Example such as this would probably have led you to this conclusion (and if not made your question simpler).

like image 81
Brits Avatar answered Oct 18 '25 08:10

Brits