Introduction: Auditing Your Own Code After It Goes Live
At the end of Part 4, the platform was finally live at https://spring-elearning.mfarim.com. I'll be honest: it felt like the finish line. It wasn't.
I keep the repository, mfarim/spring-elearning-react, public on purpose. That means anyone can read my application.yml, the seed data, the WebSocket config and the README that lists the demo accounts. So I ran a second audit with a more honest assumption: the attacker has already read every file in my repo. Looking through that lens, several defenses I was proud of in Part 2 and Part 3 turned out to be weaker than they looked.
I shipped the fixes in two pull requests:
- Pull Request #5: fix/cors-allowed-origins-production: configurable CORS origins for production.
- Pull Request #6: fix/security-hardening: 57 files, +1,510 / −446 lines. Server-side refresh rotation, a forced password change, file authorization, STOMP channel authorization, and handling the client IP properly.
In this post I'll walk you through each finding: how it could be abused, and the code I wrote to close it.
Click the diagram to open it at full size.
1. The Findings at a Glance
| # | Finding | Impact | Fixed in |
|---|---|---|---|
| 1 | CORS blocked the production origin; the first fix fell back to * with credentials | Broken prod, then an over-permissive fallback | PR #5, PR #6 |
| 2 | Client IP read from CF-Connecting-IP / X-Forwarded-For | Rate limits bypassed with one header | PR #6 |
| 3 | Rate-limit buckets stored in an unbounded ConcurrentHashMap | Heap exhaustion by rotating IPs or emails | PR #6 |
| 4 | Successful login reset the IP bucket | Attacker resets their own limit by logging in | PR #6 |
| 5 | Refresh tokens were stateless, and accepted as access tokens | No real logout; stolen tokens replayable for 7 days | PR #6 |
| 6 | Default JWT_SECRET committed in application.yml | Anyone could forge tokens on a misconfigured deploy | PR #6 |
| 7 | Seeded accounts used a documented password | Account takeover on any instance that kept the seed | PR #6 |
| 8 | /api/v1/files/** was permitAll() | Anyone with a URL could download submissions | PR #6 |
| 9 | STOMP: any teacher could monitor any exam, wildcards allowed, clients could SEND to /topic | Data leak and fake proctoring events | PR #6 |
| 10 | Swagger on, DEBUG logs, empty DB password allowed in prod | Information disclosure, weak defaults | PR #6 |
2. CORS: A Fix That Needed a Fix (PR #5)
My original SecurityConfig hard-coded localhost origins, so the production domain was blocked. In PR #5 I made the list configurable with APP_CORS_ALLOWED_ORIGINS and switched to setAllowedOriginPatterns. The catch: I also added this fallback.
// PR #5 (too permissive)
configuration.setAllowedOriginPatterns(allowedOrigins != null && !allowedOrigins.isEmpty()
? allowedOrigins : List.of("*"));
configuration.setAllowCredentials(true);
Look at it again. * together with allowCredentials(true) means any website may call the API with the user's credentials, the moment that variable is empty. In PR #6 I removed the wildcard: an empty list now means same-origin only.
// PR #6: no wildcard fallback, an empty list means same-origin only
configuration.setAllowedOriginPatterns(allowedOrigins == null ? List.of()
: allowedOrigins.stream().map(String::trim).filter(o -> !o.isEmpty()).toList());
What I took from this: a configuration default should fail closed. If I (or you) forget a variable, the app should get stricter, not looser.
3. The Real Client IP: One Header Defeated the Rate Limiter
In Part 3, my rate limiter keyed its buckets by client IP. Here's how I resolved that IP back then:
// Before PR #6: trusts headers that the client controls
public static String getClientIp(HttpServletRequest request) {
String ip = request.getHeader("CF-Connecting-IP");
if (ip == null || ip.isBlank() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
// ... first entry of the list
}
// ... X-Real-IP, then getRemoteAddr()
return ip;
}
The problem is that the client can send every one of those headers itself. A brute-force script only needs a random IP per request:
for i in $(seq 1 1000); do
curl -s -X POST https://target/api/v1/auth/login \
-H "X-Forwarded-For: 10.0.$((i / 255)).$((i % 255))" \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"guess'$i'"}'
done
Every request lands in a fresh bucket, so my "5 attempts per minute per IP" rule never fired.
The fix: resolve the IP once, at the edge, and trust only internal proxies
Luckily, Spring Boot can hand this job to Tomcat's RemoteIpValve:
server:
# Resolve the real client IP from X-Forwarded-For ONLY when the request comes from a trusted
# internal proxy (Tomcat RemoteIpValve). Default trusted ranges: 10/8, 172.16/12, 192.168/16,
# 169.254/16 and 127/8, i.e. the nginx container on the Docker network.
forward-headers-strategy: native
The valve walks X-Forwarded-For from right to left and stops at the first address that is not a trusted internal proxy. Anything a client prepends is ignored, and my application code became trivial:
public static String getClientIp(HttpServletRequest request) {
return request.getRemoteAddr(); // already resolved by RemoteIpValve
}
My site sits behind Cloudflare, so there was one more step. Without it, every visitor shows up with a Cloudflare IP and all users share the same buckets. The fix is two directives in the host Nginx from Part 4: restore the visitor IP, then overwrite the header instead of appending to it.
# /etc/nginx/sites-available/spring-elearning (host Nginx)
set_real_ip_from 173.245.48.0/20; # ...add every Cloudflare IPv4/IPv6 range
real_ip_header CF-Connecting-IP;
location / {
proxy_pass http://127.0.0.1:8088;
proxy_set_header X-Forwarded-For $remote_addr; # was $proxy_add_x_forwarded_for
}
set_real_ip_from only accepts CF-Connecting-IP from Cloudflare's ranges, so a client that connects to the VPS directly can't play that trick either.
4. Bounded Buckets and a Smarter Reset
The second problem with my Part 3 limiter was memory. I kept one Bucket per IP and per email in a ConcurrentHashMap, forever. Rotate enough fake emails and the map grows until the JVM runs out of heap. In PR #6 I moved every bucket map to a bounded, expiring Caffeine cache:
// LoginRateLimiterService (PR #6)
static Cache<String, Bucket> newBucketCache() {
return Caffeine.newBuilder()
.maximumSize(100_000)
.expireAfterAccess(Duration.ofMinutes(10))
.build();
}
The same factory now backs the three tiers in RateLimitingFilter: auth 10, exam submit 60, and general 120 requests per minute per IP.
I also found a logic bug. After a successful login I cleared both the IP bucket and the email bucket. An attacker with their own valid account could log in every few attempts and keep resetting the IP limit. Now I only clear the account's bucket:
/**
* Called after a successful login. Only the per-account bucket is reset; the per-IP bucket is kept,
* otherwise an attacker could reset their IP limit by periodically logging into their own account.
*/
public void clearRateLimit(String clientIp, String email) {
if (email != null) {
emailBuckets.invalidate(email.trim().toLowerCase());
}
}
In Part 7 I give this limiter an interface with a Redis implementation, so several backend instances can share the counters.
5. JWT Hygiene: Token Types and a Secret Nobody Knows
Two problems were hiding in JwtProvider.
Refresh tokens worked as access tokens. I signed both token types with the same key, and they had the same shape. The filter only checked the signature and the expiry, so a 7-day refresh token could be sent as Authorization: Bearer and get accepted. Now every token carries a typ claim, and every entry point checks it:
public static final String CLAIM_TYPE = "typ";
public static final String TYPE_ACCESS = "access";
public static final String TYPE_REFRESH = "refresh";
/** Valid signature, not expired, and typ=access. Refresh tokens are rejected. */
public boolean validateAccessToken(String token) {
Claims claims = parseClaims(token);
return claims != null && TYPE_ACCESS.equals(claims.get(CLAIM_TYPE, String.class));
}
The signing key was in the repo. My application.yml had secret: ${JWT_SECRET:dGhpcy1pcy1h...}. Any deployment that forgot JWT_SECRET silently used a key sitting on GitHub, and anyone could mint an admin token. I removed the default, and I refuse the known value even if someone copies it into .env:
private static final Set<String> KNOWN_PUBLIC_SECRETS = Set.of(
"dGhpcy1pcy1hLXZlcnktc2VjdXJlLTI1Ni1iaXQtbG9uZy1zZWNyZXQta2V5LWZvci1qd3Qtc2lnbmluZw=="
);
if (KNOWN_PUBLIC_SECRETS.contains(secret.trim())) {
throw new IllegalStateException("CRITICAL: app.jwt.secret uses a publicly known example value. "
+ "Generate a new one with: openssl rand -base64 32");
}
Docker Compose enforces the same rule before the JVM even starts:
JWT_SECRET: ${JWT_SECRET:?JWT_SECRET is required (openssl rand -base64 32)}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
6. Server-Side Refresh Token Rotation
I did add refresh tokens in Part 2, but they were fully stateless. "Logout" only deleted them from the browser, so a copied refresh token kept working for 7 days. In PR #6 I register every refresh token in Redis by its jti (JWT ID):
@Service
@RequiredArgsConstructor
public class RefreshTokenStore {
private static final String TOKEN_KEY = "auth:refresh:";
private static final String USER_KEY = "auth:refresh:user:";
private final StringRedisTemplate redis;
public void store(String jti, Long userId, Duration ttl) {
redis.opsForValue().set(TOKEN_KEY + jti, userId.toString(), ttl);
redis.opsForSet().add(USER_KEY + userId, jti);
redis.expire(USER_KEY + userId, ttl);
}
/** Atomically removes the jti. Returns true only if it existed and belonged to the given user. */
public boolean consume(String jti, Long userId) {
String owner = redis.opsForValue().getAndDelete(TOKEN_KEY + jti);
redis.opsForSet().remove(USER_KEY + userId, jti);
return owner != null && owner.equals(userId.toString());
}
/** Revokes every refresh token of a user (password change, account compromise). */
public void revokeAll(Long userId) { /* delete every jti in auth:refresh:user:{id} */ }
}
getAndDelete maps to Redis GETDEL, which is atomic. Two requests with the same refresh token can't both succeed: one gets the user ID, the other gets null. In the service I turned that into rotation:
// AuthService.refreshToken
Long userId = Long.parseLong(claims.getSubject());
// Rotation: each refresh token can be used exactly once; revoked/reused tokens are rejected.
if (!refreshTokenStore.consume(claims.getId(), userId)) {
throw new BadCredentialsException("Refresh token has been revoked or already used");
}
// ...check the user is still active, then issue a new access + refresh pair
Here's what that bought me:
- Logout is real now.
POST /auth/logoutrevokes thejti. - A password change logs out every device.
changePasswordcallsrevokeAll(userId)and issues one fresh pair for the current session. - Replay gets noticed. If an attacker refreshes first, the legitimate client's next refresh fails and the user lands on the login page. That's a visible signal instead of a silent takeover.
- Access tokens stay stateless. Only the refresh endpoint touches Redis; normal API calls don't.
The frontend needed two small changes to play along. SecurityConfig now returns 401 for a missing or expired token (instead of the default 403), so Axios knows when to refresh. And JwtAuthenticationFilter refuses users who are disabled or locked, even if their token hasn't expired yet.
At this stage the refresh token still traveled in the JSON body and lived in
localStorage. In Part 7 I move it into an httpOnly cookie.
7. Forced Password Change for Seeded Accounts
My seed migration created admins, teachers and students with the password password, and the README listed those accounts so people could try the demo. Fine for a demo. On a real school deployment, that's an open door.
In PR #6 I added a flag and switched it on for every account that still has the documented hash:
-- V2__security_hardening.sql
ALTER TABLE users ADD COLUMN must_change_password BOOLEAN NOT NULL DEFAULT FALSE;
UPDATE users
SET must_change_password = TRUE
WHERE password = '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi';
A filter that runs right after authentication then blocks everything except the password-change flow:
public class PasswordChangeRequiredFilter extends OncePerRequestFilter {
private static final Set<String> ALLOWED_PATHS = Set.of(
"/api/v1/auth/me", "/api/v1/auth/change-password", "/api/v1/auth/logout",
"/api/v1/auth/refresh", "/api/v1/auth/login", "/api/v1/admin/stop-impersonate");
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!demoMode && auth != null
&& auth.getPrincipal() instanceof UserPrincipal principal
&& principal.isMustChangePassword()
&& principal.getImpersonatorAdminId() == null
&& request.getRequestURI().startsWith("/api/")
&& !ALLOWED_PATHS.contains(request.getRequestURI())) {
response.setStatus(HttpStatus.FORBIDDEN.value());
// {"success":false,"code":"PASSWORD_CHANGE_REQUIRED", ...}
return;
}
chain.doFilter(request, response);
}
}
A few details I care about:
- I register it with
addFilterAfter(..., UsernamePasswordAuthenticationFilter.class), so the user is already known. - Admins impersonating a user are not blocked. Otherwise support would be impossible.
- The public demo sets
APP_DEMO_MODE=true. That skips the rule and disables password changes, so visitors can't lock each other out. - The new password can't be the old one or one of the documented defaults (
password,Student@123,Teacher@123). - On the frontend,
ProtectedRoutesends any user withmustChangePasswordto a new/change-passwordpage.
I also made public self-registration opt-in, with APP_REGISTRATION_ENABLED=false by default, because schools create accounts through the admin panel anyway.
8. Files: From Public URLs to Per-Object Authorization
This one was the most serious finding. My SecurityConfig had:
.requestMatchers("/api/v1/auth/**", "/api/v1/files/**", /* swagger... */).permitAll()
File names were random UUIDs, so the URLs were hard to guess. But every URL that ever showed up in a page, a log or a shared screenshot gave permanent anonymous access to a student's submission. In PR #6 I took /api/v1/files/** off the public list and added a dedicated authorization service:
/**
* - submissions/**: admin, the submitting student, or the teacher who owns the assignment
* - materials/**: admin/teacher, or a student of the target classroom when the material is published
* - anything else: admin/teacher only
*/
@Transactional(readOnly = true)
public boolean canRead(String filePath, UserPrincipal principal) {
if (filePath.startsWith("submissions/")) {
Optional<AssignmentSubmission> submission = submissionRepository.findFirstByFilePath(filePath);
// ...owner student, owning teacher, or admin
}
if (filePath.startsWith("materials/")) {
// ...published, and the student's classroom matches (or the material targets everyone)
}
return isAdmin || isTeacher;
}
When access is denied, FileController answers 404, not 403, so someone poking around can't tell whether a file exists. I also send downloads with Cache-Control: private, no-store, so a shared proxy or browser cache doesn't keep a copy.
Since downloads now need the Authorization header, a plain <a href> doesn't work anymore. My frontend fetches the file as a blob with the token and opens it in a new tab:
export async function openProtectedFile(url: string): Promise<void> {
// Open the tab synchronously (inside the click handler) so popup blockers allow it.
const win = window.open('', '_blank');
try {
const response = await api.get<Blob>(url.replace(/^\/api\/v1/, ''), { responseType: 'blob' });
const blobUrl = URL.createObjectURL(response.data);
if (win) {
win.opener = null;
win.location.href = blobUrl;
}
setTimeout(() => URL.revokeObjectURL(blobUrl), 60_000);
} catch (err) {
win?.close();
throw err;
}
}
Notice that I open the empty tab before the await. Browsers only allow window.open during the click event, and an await would push it outside that window.
9. WebSocket: Deny-by-Default STOMP Authorization
The live exam monitor uses STOMP over WebSocket. My original interceptor authenticated CONNECT and had exactly one rule for SUBSCRIBE:
// Before PR #6
if (destination.startsWith("/topic/exams/") && destination.endsWith("/monitor")) {
boolean canMonitor = authorities.anyMatch(a -> a.equals("ROLE_ADMIN") || a.equals("ROLE_TEACHER"));
if (!canMonitor) throw new AccessDeniedException("Forbidden");
}
That left three holes:
- Any teacher could watch any exam, including other schools' classes on a shared instance. The rule checked the role, not ownership.
- Wildcards slipped through. Spring's simple broker supports pattern subscriptions, so
SUBSCRIBE /topic/**didn't match my rule and received every event of every exam. - Clients could
SENDstraight to/topic/...and inject fakeEXAM_SUBMITTEDorVIOLATION_REPORTEDevents into a teacher's monitor.
The new interceptor handles every command explicitly and denies anything it doesn't recognize:
switch (accessor.getCommand()) {
case CONNECT, STOMP -> authenticate(accessor); // validateAccessToken + active user
case SUBSCRIBE -> authorizeSubscribe(accessor);
case SEND -> authorizeSend(accessor);
default -> { /* DISCONNECT, UNSUBSCRIBE, ACK, ... */ }
}
private void authorizeSubscribe(StompHeaderAccessor accessor) {
UserPrincipal user = requireUser(accessor.getUser());
String destination = accessor.getDestination();
// Deny-by-default. Pattern subscriptions are rejected because the simple broker
// would otherwise deliver every matching destination.
if (destination == null || destination.contains("*") || destination.contains("{") || destination.contains("?")) {
throw deny(user, destination);
}
Matcher monitor = EXAM_MONITOR_DESTINATION.matcher(destination); // ^/topic/exams/(\d+)/monitor$
if (monitor.matches()) {
Long examId = Long.valueOf(monitor.group(1));
boolean isAdmin = hasRole(user, "ROLE_ADMIN");
boolean isOwnerTeacher = hasRole(user, "ROLE_TEACHER")
&& examinationRepository.existsByIdAndTeacher_User_Id(examId, user.getId());
if (!isAdmin && !isOwnerTeacher) throw deny(user, destination);
return;
}
if (USER_QUEUE_DESTINATION.matcher(destination).matches()) return; // /user/queue/...
throw deny(user, destination);
}
private void authorizeSend(StompHeaderAccessor accessor) {
// Clients may only send to application handlers (/app/**), never straight to the broker.
if (destination == null || !destination.startsWith("/app/")) throw deny(user, destination);
}
| Destination | Who may subscribe or send |
|---|---|
/topic/exams/{id}/monitor | Subscribe: the teacher who owns exam {id}, or an admin |
/user/queue/** | Subscribe: the authenticated user (Spring resolves it per session) |
/app/** | Send: any authenticated user; handled by @MessageMapping code |
Anything with *, {, ? | Nobody |
| Anything else | Nobody |
CONNECT now uses validateAccessToken too, so a refresh token can't open a socket, and deleted or inactive users are turned away.
10. Operational Hardening
In the same PR I also tidied up a few smaller things that reduce what an attacker can learn or exploit:
| Area | Change |
|---|---|
| API docs | SPRINGDOC_ENABLED=false by default in docker-compose.prod.yml |
| Logging | com.elearning at ${LOG_LEVEL_APP:INFO} instead of DEBUG |
| Nginx (SPA container) | server_tokens off, Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=() |
| Legacy header | X-XSS-Protection: 0: the old XSS auditor is removed from modern browsers and could be abused for cross-site leaks |
| Runtime | Spring Boot 3.5.7, Node 22 for the frontend build |
| Supply chain | Dependabot for Maven, npm, Docker images and GitHub Actions |
| Deploy | deploy.sh: git pull, build all services or one (./deploy.sh backend --no-cache), up -d, prune old images |
11. Before and After
| Area | After Part 3 | After PR #6 |
|---|---|---|
| Client IP | First value of a client-controlled header | RemoteIpValve, trusted proxies only |
| Rate-limit memory | Unbounded map | Caffeine, max 100k keys, 10-minute expiry |
| Refresh token | Stateless, valid 7 days, also usable as access token | One-time jti in Redis, typ claim enforced |
| Logout | Client-side only | Server-side revoke; revoke-all on password change |
| JWT secret | Default value in application.yml | Required; known public value refused |
| Seeded passwords | Usable forever | Must be changed on first login (except demo mode) |
| File downloads | Public URLs | Per-object authorization, 404 on denial |
| STOMP | Role check on one pattern | Deny by default, ownership check, no wildcards, no direct SEND |
Conclusion & What's Next
Looking back, my first audit asked "does each feature have a security control?". The second one asked "can someone who has read the code get around it?". That second question is what found a spoofable header, an unbounded map, a committed secret and a public file route. None of them would have shown up on a feature checklist.
Writing these fixes also showed me a gap that security work alone doesn't cover: correctness under concurrency. What happens when a student hits submit in the same second the timer runs out, or double-clicks "Start exam"? That's what I dig into in Part 6.
- Live demo: https://spring-elearning.mfarim.com
- Source code: github.com/mfarim/spring-elearning-react
- Pull requests: #5, #6

Written by Muhammad Fari Madyan
Senior Full Stack Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

