1
0
Files
spring-auth-demo/jwt-authentication/scripts/curl-transcript.sh
Ankur Mhatre 4dc45d5e00 Add OAuth2 resource server project: JWT validation, JWKS and key rotation
Companion code for the follow-up article. The repository now holds two Maven
projects sharing one docs/ tree:

  jwt-authentication/       the hand-written filter application (unchanged, moved)
  oauth2-resource-server/   a resource server, a Keycloak compose, and a stub
                            issuer whose JWK Set can be mutated on command

The stub exists because Keycloak will not rotate a signing key at a chosen
second, report how many times its JWKS endpoint was fetched, or drop a key from
the published set on request - and the caching and rotation measurements need
all three. The Keycloak run confirms the same code path against a real issuer.

Findings captured under docs/output/, all from real runs:

  * The default validator stack does not check aud. A token minted for another
    service in the same realm is accepted.
  * Spring Security builds its JWKSource with refreshAheadCache(false) and
    rateLimited(false), overriding two of Nimbus's protective defaults, and
    enables Nimbus caching only when NO Spring cache was supplied - so
    supplying one removes the five-minute expiry.
  * A key retired from the JWK Set stops being accepted at t+300s with the
    default cache, and never with a Spring cache that has no TTL.
  * 25 tokens carrying an unknown kid produce 25 JWKS fetches at the issuer,
    through permitAll() endpoints included.
  * A hyphenated client id in an authorities-claim-expression parses as
    subtraction; the SpelEvaluationException is swallowed and logged at TRACE.
  * A clientScopes key in a Keycloak realm import replaces the built-in scopes
    rather than adding to them.

New docs chapters 12-18. README covers both projects. Existing docs and scripts
updated for the new paths; no docs/output/ file from the first article moved, so
links in the published article still resolve.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013f7f2XZXrQ6gW3RtZE187t
2026-08-23 11:00:56 +00:00

113 lines
4.9 KiB
Bash
Executable File

#!/usr/bin/env bash
# Regenerates ../docs/output/curl-transcript-hs256.txt against a running instance.
# Usage: ./scripts/curl-transcript.sh [base-url]
set -u
BASE="${1:-http://localhost:8080}"
hr() { printf '\n%s\n' "--------------------------------------------------------------------------"; }
step(){ hr; printf '# %s\n\n' "$1"; }
# Print status line, the security-relevant headers, and the body.
show() {
local out
out=$(curl -sS -D /tmp/.h -o /tmp/.b -w '%{http_code}' "$@")
printf 'HTTP %s\n' "$out"
grep -iE '^(www-authenticate|content-type|set-cookie):' /tmp/.h | sed 's/\r$//'
if [ -s /tmp/.b ]; then
python3 -m json.tool < /tmp/.b 2>/dev/null || cat /tmp/.b
echo
fi
}
jwt_part() { # $1=token $2=0|1 -> pretty-print header or payload
echo "$1" | cut -d. -f$(( $2 + 1 )) \
| tr '_-' '/+' | sed 's/$/==/' | base64 -d 2>/dev/null \
| python3 -m json.tool 2>/dev/null
}
echo "=========================================================================="
echo " jwt-auth-demo - curl transcript"
echo " target : $BASE"
echo "=========================================================================="
step "1. Public endpoint, no token. permitAll() means the filter chain lets it through."
show "$BASE/api/public/ping"
step "2. Protected endpoint, no token. 401 - we do not know who you are."
show "$BASE/api/me"
step "3. Wrong password. Still 401, and the body says nothing about which half was wrong."
show -X POST "$BASE/api/auth/login" -H 'Content-Type: application/json' \
-d '{"username":"alice","password":"wrong-password"}'
step "4. Locked account. 401 with the identical body - no account-state oracle."
show -X POST "$BASE/api/auth/login" -H 'Content-Type: application/json' \
-d '{"username":"locked","password":"locked-password"}'
step "5. Login as alice (ROLE_USER, SCOPE_profile:read)."
show -X POST "$BASE/api/auth/login" -H 'Content-Type: application/json' \
-d '{"username":"alice","password":"alice-password"}'
ALICE=$(python3 -c "import json;print(json.load(open('/tmp/.b'))['accessToken'])")
ALICE_REFRESH=$(python3 -c "import json;print(json.load(open('/tmp/.b'))['refreshToken'])")
step "6. What is actually inside that token (base64url decode - no signature check)."
echo "--- JOSE header ---"
jwt_part "$ALICE" 0
echo "--- claims ---"
jwt_part "$ALICE" 1
step "7. The same protected endpoint, now with the token. 200."
show "$BASE/api/me" -H "Authorization: Bearer $ALICE"
step "8. alice hits an ADMIN endpoint. 403, not 401 - we know who she is, she may not."
show "$BASE/api/admin/stats" -H "Authorization: Bearer $ALICE"
step "9. Same request with a scope-based rule (@PreAuthorize). Also 403."
show "$BASE/api/reports" -H "Authorization: Bearer $ALICE"
step "10. Login as root and repeat. 200."
show -X POST "$BASE/api/auth/login" -H 'Content-Type: application/json' \
-d '{"username":"root","password":"root-password"}'
ROOT=$(python3 -c "import json;print(json.load(open('/tmp/.b'))['accessToken'])")
show "$BASE/api/admin/stats" -H "Authorization: Bearer $ROOT"
step "11. Tampered payload, original signature. 401 invalid_token."
HDR=$(echo "$ALICE" | cut -d. -f1); SIG=$(echo "$ALICE" | cut -d. -f3)
FORGED_PAYLOAD=$(echo "$ALICE" | cut -d. -f2 | tr '_-' '/+' | sed 's/$/==/' | base64 -d 2>/dev/null \
| sed 's/"roles":\["USER"\]/"roles":["ADMIN"]/' | base64 -w0 | tr '/+' '_-' | tr -d '=')
show "$BASE/api/admin/stats" -H "Authorization: Bearer $HDR.$FORGED_PAYLOAD.$SIG"
step "12. Garbage where a token should be. 401, and note it is NOT 400."
show "$BASE/api/me" -H "Authorization: Bearer not-a-jwt"
step "13. Authorization header with no Bearer scheme. The resolver sees no token at all,\n# so this is an authorization failure, not a token failure - note the bare realm."
show "$BASE/api/me" -H "Authorization: $ALICE"
step "14. A refresh token presented as an access token. 401 - the token_type claim."
show "$BASE/api/me" -H "Authorization: Bearer $ALICE_REFRESH"
step "15. Refresh with rotation. New access token, new refresh token."
show -X POST "$BASE/api/auth/refresh" -H 'Content-Type: application/json' \
-d "{\"refreshToken\":\"$ALICE_REFRESH\"}"
ALICE2=$(python3 -c "import json;print(json.load(open('/tmp/.b'))['accessToken'])")
step "16. Replay the spent refresh token. 401 - rotation makes replay detectable."
show -X POST "$BASE/api/auth/refresh" -H 'Content-Type: application/json' \
-d "{\"refreshToken\":\"$ALICE_REFRESH\"}"
step "17. Logout revokes the presented access token by its jti."
show -X POST "$BASE/api/auth/logout" -H "Authorization: Bearer $ALICE2"
show "$BASE/api/auth/revocations" -H "Authorization: Bearer $ROOT"
step "18. The revoked token, still cryptographically valid, is now refused."
show "$BASE/api/me" -H "Authorization: Bearer $ALICE2"
step "19. The real filter order, read from FilterChainProxy at runtime."
show "$BASE/api/public/filters"
step "20. SecurityContext across a thread boundary."
show "$BASE/api/async-demo" -H "Authorization: Bearer $ROOT"
hr
echo "# end of transcript"