A symmetric signing algorithm uses one shared secret key both to create a message authentication code or signature and to validate it. In JWTs, HS256 combines HMAC with SHA-256 to protect message integrity and authenticity. section 7.2.2
The shared key must exist wherever tokens are issued or validated, increasing the risk of leakage. Short or weak secrets also make HS256 signatures vulnerable to brute-force attacks; an exposed signing key can enable forged tokens. section 7.2.2 section 8.2
Signing a JWT with HS256
A PyJWT issuer can call jwt.encode with a payload, the shared key "password", and algorithm="HS256". The resulting token can be inspected and its signature verified by supplying the same secret to a JWT inspection tool. The example makes the operational requirement clear: every verifier needs access to the signing secret. section 8.2
Evaluate a symmetric JWT design by checking:
- Whether the signing secret is long and strong enough to resist brute-force guessing. section 7.2.2
- How many services store or require the secret for signature validation. section 7.2.2 section 8.2
- Whether asymmetric signing better limits key exposure: a private key signs, while a public key verifies. section 7.2.2
Listing 8.4 Issuing a JWT with PyJWT
# file: ch08/jwt_generator_pyjwt_hs256.py
from datetime import datetime, timezone, timedelta
import jwt
now = datetime.now(timezone.utc)
payload = {
"iss": "https://auth.apithreats.com",
"sub": "23456543",
"aud": "https://apithreats.com/api",
"iat": now,
"exp": (now + timedelta(hours=1))
}
print(jwt.encode(payload=payload, key="password", algorithm="HS256"))
Inspect the focused PyJWT example showing HS256 token issuance and the shared secret passed to the encoder. section 8.2
