Why a Go JWT Parser Needs an Explicit Algorithm List
A JWT key function decides which key to verify with, but the token's own header decides which algorithm to verify with. If your code never limits the second part, the attacker gets to choose it. The classic result: a token signed with HMAC, using your RSA public key as the secret, and your server accepting it.
The code that looks fine
This is a very common shape. The public key is loaded once, and the key func hands it back:
var pubPEM = mustReadFile("public.pem") // []byte, PEM-encoded RSA public key
func keyFunc(t *jwt.Token) (any, error) {
return pubPEM, nil
}
func verify(raw string) (*jwt.Token, error) {
return jwt.Parse(raw, keyFunc)
}
It reads as "verify with this key". What it does is "verify with this key, using whatever method the token names". The library reads the alg header, finds the matching signing method, and calls it with whatever your key func returned.
How the forgery works
The attacker needs nothing secret, because your public key is public. The steps:
- Fetch the public key (a JWKS endpoint, a certificate, a docs page).
- Write a payload claiming to be an admin.
- Set the header to
{"alg":"HS256"}. - Compute an HMAC-SHA256 over the token, using the exact bytes your server holds as the "key".
Your server sees HS256, runs HMAC with the PEM bytes as the secret, gets the same answer, and the signature checks out. The key was never the problem; the algorithm choice was handed to the sender.
Quick detour: why does HMAC accept that at all?
HMAC has no concept of key types. A secret is just bytes, and a PEM file is just bytes. Nothing in the primitive says "this looks like a public key, refuse". Asymmetric and symmetric schemes share a header field but have opposite trust models: with RSA, anyone may verify; with HMAC, anyone who can verify can also forge. Letting the token pick between them swaps one model for the other.
The fix: say which algorithms you accept
With golang-jwt v5, pass jwt.WithValidMethods. The parser then rejects any token whose alg is not on the list, before your key func is trusted with it.
func verify(raw string) (*jwt.Token, error) {
return jwt.Parse(raw, keyFunc,
jwt.WithValidMethods([]string{"RS256"}),
jwt.WithIssuer("https://auth.example.com"),
jwt.WithAudience("my-api"),
jwt.WithExpirationRequired(),
)
}
The list is deliberately short. If you issue RS256 tokens, accept RS256. Do not list "everything asymmetric" out of tidiness, and certainly do not mix HS and RS families in one parser.
Also make the key func check, as a second lock
The key func gets the parsed token, so it can refuse a mismatch itself. That is worth having when the key comes from somewhere you do not fully control, such as a JWKS lookup by kid.
func keyFunc(t *jwt.Token) (any, error) {
if _, ok := t.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method %q", t.Header["alg"])
}
return pubKey, nil // *rsa.PublicKey, already parsed
}
Note that pubKey here is a parsed *rsa.PublicKey, not raw PEM bytes. That matters more than it looks, as the next section explains.
Typed keys help, but do not replace the list
In recent golang-jwt versions the HMAC method insists on a []byte key. Hand it an *rsa.PublicKey and verification fails with an invalid key type error. So parsing your key into its real type before returning it closes the exact hole above, and that is a good habit.
It is a side effect of types, though, not a policy. Returning raw bytes, or a key whose type happens to suit the wrong algorithm, brings the problem straight back. Older libraries and other languages behave differently again. An explicit list works the same everywhere and states your intent in one line.
What the list does not cover
- A
kidchosen by the attacker still selects among your keys, so only look it up in a fixed set you control, never fetch a URL from the header. - The algorithm list says nothing about expiry, issuer or audience; add those options as shown.
- If a JWKS entry carries its own
alg, compare it with the token's rather than trusting either on its own.
The unsigned alg: none case is a separate failure mode with its own cause; this one is purely about which real algorithm gets used. A one-line allow-list stops both.
One test is worth keeping: sign a token with HS256 using your public key bytes, feed it to your verifier, and assert it fails. If that test ever passes, you want to know before someone else does.