Myth: If a JWT Decodes, It Is Safe
A JWT is three base64 parts, and decoding it is trivial. That convenience creates a dangerous shortcut: if the token decodes, treat it as valid. I tested that belief with a real run, and it failed twice. Full run in this Short: https://youtu.be/1aLXVqGiOZk What decode-only accepted I built a decode-only check in Node and fed it 6 tokens. It accepted an expired token and a token signed with the…
A JWT is a three-part base64 string, and decoding it is simple. This ease of decoding leads to a risky shortcut: assuming a decodable token is valid. To test this assumption, I conducted a real-world experiment and found it failed twice. The full experiment can be found in this video: https://youtu.be/1aLXVqGiOZk
Using Node.js, I created a decode-only check and ran it against six different tokens. Surprisingly, the decode-only check accepted an expired token and a token signed with the incorrect key. Decoding only examines the token's payload; it does not verify the signer or the token's validity. Consequently, both tokens appeared perfectly valid to the decode-only check.
Verification, on the other hand, follows a specific order. First, it recomputes the signature using the header, payload, and a secret key, then compares it to the token's signature. If the tokens are signed with different keys, the verification process will fail, regardless of the token's validity. Next, it checks the token's expiration, looking at both the exp (expiration) and nbf (not before) claims against the current time.
If the token has expired, it fails the verification process. Only after both the signature and time claims pass is the payload trusted.
In this experiment, I used the HS256 algorithm with Node's crypto module, a fixed demo clock, and six different tokens. Verification rejected all tokens that were accepted by the decode-only check. The key takeaway from this experiment is that decoding should only be used for reading purposes, while verification is necessary for trusting a token. It is essential not to branch based on a payload that has not been verified.
While this experiment focused on the HS256 algorithm, there are other aspects to consider in production environments, such as RS256, key rotation, clock skew, and revocation. Using a maintained JWT library can help ensure secure handling of JWTs. For a demonstration of this experiment, watch the real terminal output in this video: https://youtu.be/1aLXVqGiOZk (the narration is AI-generated, but the test output is from a real run). The full 17-line demo file can be found here: https://youtu.be/OGD-QY_qzy0
If you found this experiment interesting or have suggestions for what to build and break next, please let me know in the comments on Ship Stack AI's YouTube channel.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to
More from Dev.to on urgent.news
Report a problem with this story
Get the day's news by email. Daily, weekly or monthly. Sign up