1
0

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
This commit is contained in:
2026-08-23 11:00:56 +00:00
parent 4a8dab6739
commit 4dc45d5e00
101 changed files with 4087 additions and 64 deletions

View File

@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# Reproduces the "permitAll() endpoint still returns 403" failure.
# Requires: --spring.profiles.active=hs256,csrfon
set -u
BASE="${1:-http://localhost:8080}"
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):' /tmp/.h | sed 's/\r$//'
[ -s /tmp/.b ] && { python3 -m json.tool < /tmp/.b 2>/dev/null || cat /tmp/.b; echo; }
}
hr(){ printf '\n%s\n' "--------------------------------------------------------------------------"; }
echo "=========================================================================="
echo " jwt-auth-demo - CSRF vs permitAll()"
echo " app started with: --spring.profiles.active=hs256,csrfon"
echo "=========================================================================="
hr; echo "# A. The login endpoint is permitAll(). POST it anyway."
echo "# 403 - and nothing in the authorization rules explains why."
echo
show -X POST "$BASE/api/auth/login" -H 'Content-Type: application/json' \
-d '{"username":"alice","password":"alice-password"}'
hr; echo "# B. GET on the same permitAll() path family works. Only unsafe methods break."
echo
show "$BASE/api/public/ping"
hr; echo "# C. The filter chain, with CsrfFilter present. Count the positions:"
echo "# CsrfFilter is 5th, AuthorizationFilter is last. The request never"
echo "# reaches the filter that knows about permitAll()."
echo
show "$BASE/api/public/filters"
hr; echo "# end"

View File

@@ -0,0 +1,112 @@
#!/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"

View File

@@ -0,0 +1,32 @@
#!/usr/bin/env bash
# Requires: --spring.profiles.active=hs256,shortlived (2-second access tokens)
set -u
BASE="${1:-http://localhost:8080}"
show() {
local out; out=$(curl -sS -D /tmp/.h -o /tmp/.b -w '%{http_code}' "$@")
printf 'HTTP %s\n' "$out"
grep -iE '^www-authenticate:' /tmp/.h | sed 's/\r$//'
[ -s /tmp/.b ] && { python3 -m json.tool < /tmp/.b 2>/dev/null | head -6 || cat /tmp/.b; }
echo
}
hr(){ printf '\n%s\n' "--------------------------------------------------------------------------"; }
echo "=========================================================================="
echo " jwt-auth-demo - token expiry and the 60-second clock skew"
echo " profiles: hs256,shortlived (access-token-ttl = 2s)"
echo "=========================================================================="
TOK=$(curl -sS -X POST "$BASE/api/auth/login" -H 'Content-Type: application/json' \
-d '{"username":"alice","password":"alice-password"}' | python3 -c 'import json,sys;print(json.load(sys.stdin)["accessToken"])')
hr; echo "# T+0s - fresh token"; echo; show "$BASE/api/me" -H "Authorization: Bearer $TOK"
hr; echo "# T+5s - exp has passed, but JwtTimestampValidator allows 60s of clock skew"
echo "# by default, so the token is STILL accepted. This surprises people"
echo "# who write a test that sleeps past exp and expects a 401."
echo; sleep 5; show "$BASE/api/me" -H "Authorization: Bearer $TOK"
hr; echo "# T+65s - past exp + the 60s skew window. Now it is refused."
echo; sleep 60; show "$BASE/api/me" -H "Authorization: Bearer $TOK"
hr; echo "# end"

View File

@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Compares the built-in resource server with and without a token_type validator.
# Requires two runs; see docs/09-manual-filter-vs-resource-server.md
set -u
BASE="${1:-http://localhost:8080}"
LABEL="${2:-resourceserver}"
show() {
local out; out=$(curl -sS -D /tmp/.h -o /tmp/.b -w '%{http_code}' "$@")
printf 'HTTP %s\n' "$out"
grep -iE '^www-authenticate:' /tmp/.h | sed 's/\r$//'
[ -s /tmp/.b ] && { python3 -m json.tool < /tmp/.b 2>/dev/null | head -10 || cat /tmp/.b; echo; }
}
hr(){ printf '\n%s\n' "--------------------------------------------------------------------------"; }
echo "=========================================================================="
echo " jwt-auth-demo - built-in resource server"
echo " profiles: $LABEL"
echo "=========================================================================="
R=$(curl -sS -X POST "$BASE/api/auth/login" -H 'Content-Type: application/json' \
-d '{"username":"alice","password":"alice-password"}')
ACCESS=$(echo "$R" | python3 -c 'import json,sys;print(json.load(sys.stdin)["accessToken"])')
REFRESH=$(echo "$R" | python3 -c 'import json,sys;print(json.load(sys.stdin)["refreshToken"])')
hr; echo "# 1. The filter chain. Note BearerTokenAuthenticationFilter in place of our"
echo "# hand-written JwtAuthenticationFilter - same slot, framework-owned."
echo; show "$BASE/api/public/filters"
hr; echo "# 2. Access token -> 200."; echo; show "$BASE/api/me" -H "Authorization: Bearer $ACCESS"
hr; echo "# 3. Non-admin on an admin route -> 403 insufficient_scope."
echo; show "$BASE/api/admin/stats" -H "Authorization: Bearer $ACCESS"
hr; echo "# 4. REFRESH token presented as an access token."
echo "# This is the line to watch when comparing the two runs."
echo; show "$BASE/api/me" -H "Authorization: Bearer $REFRESH"
hr; echo "# end"

View File

@@ -0,0 +1,45 @@
#!/usr/bin/env bash
# Requires: --spring.profiles.active=rs256
set -u
BASE="${1:-http://localhost:8080}"
show() {
local out; out=$(curl -sS -D /tmp/.h -o /tmp/.b -w '%{http_code}' "$@")
printf 'HTTP %s\n' "$out"
grep -iE '^www-authenticate:' /tmp/.h | sed 's/\r$//'
[ -s /tmp/.b ] && { python3 -m json.tool < /tmp/.b 2>/dev/null || cat /tmp/.b; echo; }
}
jwt_part(){ echo "$1" | cut -d. -f$(( $2 + 1 )) | tr '_-' '/+' | sed 's/$/==/' | base64 -d 2>/dev/null | python3 -m json.tool 2>/dev/null; }
hr(){ printf '\n%s\n' "--------------------------------------------------------------------------"; }
echo "=========================================================================="
echo " jwt-auth-demo - RS256 variant"
echo " profiles: rs256 (private key signs, public key / JWKS verifies)"
echo "=========================================================================="
hr; echo "# 1. The public half, published as a JWK Set. No private material here -"
echo "# n and e only. Any number of resource servers can poll this."
echo; show "$BASE/.well-known/jwks.json"
hr; echo "# 2. Login. Same endpoint, same request, different signature algorithm."
echo; show -X POST "$BASE/api/auth/login" -H 'Content-Type: application/json' \
-d '{"username":"root","password":"root-password"}'
TOK=$(python3 -c "import json;print(json.load(open('/tmp/.b'))['accessToken'])")
hr; echo "# 3. The JOSE header now carries alg=RS256 and the kid that selects the key."
echo; jwt_part "$TOK" 0
hr; echo "# 4. Token length. RS256 signatures are 256 bytes; HS256 signatures are 32."
echo
printf ' RS256 access token: %s characters\n' "${#TOK}"
printf ' signature segment : %s characters\n' "$(echo "$TOK" | cut -d. -f3 | wc -c)"
hr; echo "# 5. It works exactly the same from the caller's side."
echo; show "$BASE/api/me" -H "Authorization: Bearer $TOK"
hr; echo "# 6. Tampered payload, original signature -> 401, same as HS256."
HDR=$(echo "$TOK" | cut -d. -f1); SIG=$(echo "$TOK" | cut -d. -f3)
FORGED=$(echo "$TOK" | cut -d. -f2 | tr '_-' '/+' | sed 's/$/==/' | base64 -d 2>/dev/null \
| sed 's/"sub":"root"/"sub":"mallory"/' | base64 -w0 | tr '/+' '_-' | tr -d '=')
echo; show "$BASE/api/me" -H "Authorization: Bearer $HDR.$FORGED.$SIG"
hr; echo "# end"

View File

@@ -0,0 +1,42 @@
#!/usr/bin/env bash
# Regenerates every file under ../docs/output/ from a real run.
# Usage: ./scripts/run-all.sh
set -eu
cd "$(dirname "$0")/.."
echo "==> mvn test"
{
echo "=========================================================================="
echo " jwt-auth-demo - test run"
echo "=========================================================================="
echo
mvn -B test 2>&1 | grep -E '^\[INFO\] (Running|Tests run)|^\[ERROR\]|BUILD (SUCCESS|FAILURE)' \
| sed 's/^\[INFO\] //'
echo
echo "JDK : $(java -version 2>&1 | grep -v JAVA_TOOL | head -1)"
echo "Boot : 4.1.1"
echo "Security : 7.1.1"
} > ../docs/output/test-run.txt
echo "==> hs256 (manual filter) transcript"
./scripts/run.sh hs256 >/dev/null && ./scripts/curl-transcript.sh > ../docs/output/curl-transcript-hs256.txt 2>&1
echo "==> rs256 transcript"
./scripts/run.sh rs256 >/dev/null && ./scripts/rs256-demo.sh > ../docs/output/rs256-demo.txt 2>&1
echo "==> csrf vs permitAll"
./scripts/run.sh hs256,csrfon >/dev/null && ./scripts/csrf-demo.sh > ../docs/output/csrf-vs-permitall.txt 2>&1
echo "==> expiry and clock skew (takes ~70s)"
./scripts/run.sh hs256,shortlived >/dev/null && ./scripts/expiry-demo.sh > ../docs/output/expiry-and-clock-skew.txt 2>&1
echo "==> built-in resource server, without and with the token_type validator"
./scripts/run.sh hs256,resourceserver >/dev/null \
&& ./scripts/resource-server-demo.sh http://localhost:8080 "hs256,resourceserver" \
> ../docs/output/resource-server-loose.txt 2>&1
./scripts/run.sh hs256,resourceserver,strict >/dev/null \
&& ./scripts/resource-server-demo.sh http://localhost:8080 "hs256,resourceserver,strict" \
> ../docs/output/resource-server-strict.txt 2>&1
for p in $(ps -eo pid,cmd | grep '[J]wtAuthDemoApplication' | awk '{print $1}'); do kill -9 "$p" || true; done
echo "==> done. docs/output/ regenerated."

View File

@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# Starts the app on a clean port 8080 with the given profiles.
# Usage: ./scripts/run.sh [profiles] e.g. ./scripts/run.sh rs256,resourceserver
set -eu
PROFILES="${1:-hs256}"
for p in $(ps -eo pid,cmd | grep '[J]wtAuthDemoApplication' | awk '{print $1}'); do kill -9 "$p" || true; done
sleep 2
setsid nohup mvn -B -o org.springframework.boot:spring-boot-maven-plugin:run \
-Dspring-boot.run.profiles="$PROFILES" > "/tmp/app-${PROFILES//,/-}.log" 2>&1 < /dev/null &
for i in $(seq 1 60); do
if curl -s -o /dev/null http://localhost:8080/api/public/ping 2>/dev/null; then
echo "started with profiles: $PROFILES"; exit 0
fi
sleep 2
done
echo "failed to start; see /tmp/app-${PROFILES//,/-}.log" >&2; exit 1