Home  >  Article  >  Backend Development  >  How does JWT resolve claim validity and errors?

How does JWT resolve claim validity and errors?

王林
王林forward
2024-02-06 11:12:03408browse

JWT 如何解析声明有效性和错误?

Question content

I am creating access, refresh token logic and I want to check if the access token is valid (not edited) even if it has Expired. If the token expires, Go will return an error and invalidate the token. So I check if the given error matches ErrTokenExpired.

Can I be 100% sure that if the token is invalid, then err will not be zero, so I can remove the if !tkn.Valid{...?

Is this generally a good approach or will the edited token pass my validation?

func VerifyJWT(jwtString, secret string) (*jwt.Token, *Claims, error) {
    claims := &Claims{}
    tkn, err := jwt.ParseWithClaims(jwtString, claims, func(token *jwt.Token) (interface{}, error) {
        return []byte(os.Getenv(secret)), nil
    })
    return tkn, claims, err
}
_, accClaims, err1 := VerifyJWT(req.Access, "ACCESS_SECRET")
    if err1 != nil && err1.Error()[:16] != jwt.ErrTokenExpired.Error()[:16] {
        WriteJSON(w, http.StatusBadRequest, APIError{Error: "invalid token access" + err1.Error()})
        return
    }

Correct answer


jwt token is safe if you have two points in your code:

1-Choose a good algorithm
2- Create a random key

If the token changes or times out, these two options can help you, VerifyJWTReturn an error!

Note: Always need to check for errors and return a good response to the client.

NOTE (Improve your code): To check if an error is ErrTokenExpired, use the errors pkg.

Your example:

// import "errors"


_, accClaims, err := VerifyJWT(req.Access, "ACCESS_SECRET")
if errors.Is(err, jwt.ErrTokenExpired) {
        // continue progress
}

if err != nil {
    WriteJSON(w, http.StatusUnauthorized, APIError{Error: err.Error()})
    return
}

The above is the detailed content of How does JWT resolve claim validity and errors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete