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

How does JWT resolve claim validity and errors?

王林
Release: 2024-02-06 11:12:03
forward
502 people have browsed it

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
}
Copy after login
_, 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
    }
Copy after login


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
}
Copy after login

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!

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