Token Validation
Source: Dev.to
Overview
The process of validating a JWT involves:
- Parsing the token string.
- Decoding the header and payload.
- Verifying the signature using the appropriate secret/key.
- Populating a custom
Claimsstruct with the payload data. - Returning the claims if the token is valid, otherwise returning an error.
Claims Struct
type Claims struct {
UserID string `json:"user_id"`
jwt.StandardClaims
}
The Claims struct embeds jwt.StandardClaims and adds a custom UserID field.
Secret Key
secretKey := GetJWTKey()
GetJWTKey()retrieves the global secret key used for signing and validating JWTs.- In this example the algorithm is HS256, so the key is a
[]byte. - The same key is used for all users.
Parsing the Token
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return secretKey, nil
})
How ParseWithClaims Works
- Split the token into three parts: header, payload, and signature.
- Decode the header and payload into a temporary
jwt.Tokenstruct. - Call the key function (the anonymous function above) to obtain the verification key (
secretKey). - Recalculate the expected signature using:
- The decoded header and payload.
- The secret key.
- The algorithm specified in
token.Method(e.g., HS256).
- Compare the recalculated signature with the signature from the token.
- If they match, set
token.Valid = trueand populate the providedClaimsstruct with the payload data.
Internal Token Representation
type Token struct {
Raw string // The original token string
Method jwt.SigningMethod // Signing algorithm (e.g., HS256)
Header map[string]interface{} // Header fields (e.g., "alg")
Claims jwt.Claims // Claims (populated with &Claims{})
Signature string // Base64‑encoded signature part
Valid bool // Result of signature & claim validation
}
Using the Parsed Claims
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
return claims, nil
}
- The generic
token.Claimsis type‑asserted to the concrete*Claimsstruct. - If the token is valid, the function returns the populated
claims; otherwise, it returns an error.
TL;DR Flow
jwt.ParseWithClaimsreceivestokenString.- Splits the token → header, payload, signature.
- Decodes header + payload into a temporary
jwt.Token. - Calls the key function → returns
secretKey. - Recalculates the signature using
secretKeyand the algorithm from the header. - Compares the recalculated signature with the token’s signature.
- Match → token is valid,
token.Valid = true. - No match → token is invalid.
- Match → token is valid,
- Fills the provided
&Claims{}struct with payload data. - Returns the claims (or an error) to the caller.