Invalid memory address or nil pointer dereference validation jwt expiration time

WBOY
Release: 2024-02-08 22:10:18
forward
438 people have browsed it

无效的内存地址或 nil 指针取消引用验证 jwt 过期时间

php editor Xiaoxin introduces you to the common problems when verifying the JWT expiration time. When using JWT for authentication, we often need to verify whether the token has expired. However, sometimes we may encounter some errors such as invalid memory address or nil pointer dereference. These errors can cause token validation to fail. This article will analyze the causes of these problems for you and provide solutions to help you successfully verify the expiration time of JWT.

Question content

I am using jwt token to log in using golang, so far everything is going fine, it checks what time is left on the token, if there is no token, it A message will be sent But I have two problems, if the token is invalid or the expiration time has passed, it shows this error:

The line carrying the error is like this claims := token.claims.(*jwtcustomclaims)

My jwtcustomclaims variable is like this:

type jwtcustomclaims struct {
    user     string `json:"email"`
    nombre   string `json:"nombre"`
    apellido string `json:"apellido"`
    edad     int    `json:"edad"`
    genero   string `json:"genero"`
    rol      string `json:"rol"`
    jwt.standardclaims
}
Copy after login

Using this structure will also generate a token. The complete function to check the token is this

func ValidateToken(tokenString string, secretKey string, c *fiber.Ctx) (*jwt.Token, error) {
    token, err := jwt.ParseWithClaims(tokenString, &jwtCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
        return []byte(secretKey), nil
    })

    if err != nil {
        if err == jwt.ErrSignatureInvalid {
            return nil, err
        }
        return nil, c.JSON(fiber.Map{
            "message": "Unauthorized",
            "code":    400,
        })

    }

    _, ok := token.Claims.(*jwtCustomClaims)
    if !ok || !token.Valid {
        return nil, c.JSON(fiber.Map{
            "message": "Unauthorized",
            "code":    400,
        })
    }

    return token, nil
}

func TokenMiddleware(c *fiber.Ctx) error {
    tokenString := c.Get("Authorization")
    if tokenString == "" {
        return c.JSON(fiber.Map{
            "message": "No token",
            "code":    400,
        })
    }

    // Separa el token del encabezado "Bearer"
    tokenString = strings.ReplaceAll(tokenString, "Bearer ", "")

    token, err := ValidateToken(tokenString, os.Getenv("SECRET"), c)
    if err != nil {
        return err
    }

        claims := token.Claims.(*jwtCustomClaims)

        expiresIn := time.Until(time.Unix(claims.ExpiresAt, 0))
        if expiresIn > 0 {
            return c.JSON(fiber.Map{
                "message":    "Token is valid",
                "expires_in": expiresIn.String(),
                "is_expired": false,
            })
            //return c.Next()
        } else {
            return c.JSON(fiber.Map{
                "message":    "Token is valid but expired",
                "expires_in": 0,
                "is_expired": true,
            })
        }
}
Copy after login

To check if it validates the token, I just tried putting in another type of token from another project and writing it wrong just to test, but it sends a console error. For the expiration time, I looked at the errors online and the solution was to write like this if claims == nil but it doesn't work and I don't know what else to do

solution

Please test it:

func ValidateToken(tokenString string, secretKey string, c *fiber.Ctx) (jwtCustomClaims, error) {
    var claims jwtCustomClaims
    token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
        return []byte(secretKey), nil
    })
    if err != nil {
        if err == jwt.ErrSignatureInvalid {
            return jwtCustomClaims{}, err
        }
        return jwtCustomClaims{}, c.JSON(fiber.Map{
            "message": "Unauthorized",
            "code":    400,
        })

    }

    if !token.Valid {
        return jwtCustomClaims{}, c.JSON(fiber.Map{
            "message": "Unauthorized",
            "code":    400,
        })
    }

    return claims, nil
}

func TokenMiddleware(c *fiber.Ctx) error {
    .
    .
    .

    claims, err := ValidateToken(tokenString, os.Getenv("SECRET"), c)
    if err != nil {
        return err
    }

    expiresIn := time.Until(time.Unix(claims.ExpiresAt, 0))

    .
    .
    .
}
Copy after login

The above is the detailed content of Invalid memory address or nil pointer dereference validation jwt expiration time. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!