Runnable companion for https://ankurm.com/spring-security-7-1-jwt-authentication-guide/ - login -> token issue -> OncePerRequestFilter -> SecurityContext, end to end - HS256 and RS256 variants (RS256 publishes a real JWKS endpoint) - the same API secured by the built-in oauth2ResourceServer().jwt(), for comparison - 11 documentation chapters under docs/, interlinked with the code - docs/output/ is real captured output, regenerated by scripts/run-all.sh - 13 passing tests pinning the 401-vs-403 contract and the CSRF failure Verified against Spring Boot 4.1.1, Spring Security 7.1.1, JDK 25.0.4.1.
33 lines
1.6 KiB
Bash
Executable File
33 lines
1.6 KiB
Bash
Executable File
#!/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"
|