Spring Security 7.1 JWT authentication on Spring Boot 4.1
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.
This commit is contained in:
36
scripts/csrf-demo.sh
Executable file
36
scripts/csrf-demo.sh
Executable 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"
|
||||
112
scripts/curl-transcript.sh
Executable file
112
scripts/curl-transcript.sh
Executable file
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates docs/output/curl-transcript.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"
|
||||
32
scripts/expiry-demo.sh
Executable file
32
scripts/expiry-demo.sh
Executable 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"
|
||||
38
scripts/resource-server-demo.sh
Executable file
38
scripts/resource-server-demo.sh
Executable 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"
|
||||
45
scripts/rs256-demo.sh
Executable file
45
scripts/rs256-demo.sh
Executable 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"
|
||||
42
scripts/run-all.sh
Executable file
42
scripts/run-all.sh
Executable 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."
|
||||
16
scripts/run.sh
Executable file
16
scripts/run.sh
Executable 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
|
||||
Reference in New Issue
Block a user