SPRING SECURITY / 04

How Spring Security works

Authentication, authorisation and the lab's specific decisions.

Authentication: checking who you are

In a real deployment, login receives email and password over HTTPS. AuthController normalises the email and creates an unauthenticated UsernamePasswordAuthenticationToken. AuthenticationManager is a ProviderManager with DaoAuthenticationProvider: it loads UserDetails by email, checks enabled and compares the password with PasswordEncoder.matches. The entity is not returned to the browser; UserResponse excludes passwordHash.

BCrypt is an adaptive salted hash; it cannot be decrypted to recover the password. Hashes of the same password can differ because of their salt. A password change computes a new hash. The implementation uses BCryptPasswordEncoder with its default cost and limits input to 72 UTF-8 bytes, alongside DTO character rules.

JWT: what is signed and verified

text
cabecera.payload.firma

Cabecera: {"alg":"HS256"}
Payload ilustrativo:
{
  "iss": "security-lab",
  "sub": "3",
  "iat": 1800000000,
  "exp": 1800000900,
  "role": "USER"
}

Sub is the account's stable id, not its email. Iat and exp are Unix seconds; expiresIn is the duration in seconds returned in the response. NimbusJwtEncoder signs with HS256. NimbusJwtDecoder requires that algorithm and verifies signature, issuer security-lab and timestamps with zero tolerance configured in JwtTimestampValidator.

Protected request: filters before the controller

  1. Axios adds Authorization: Bearer ....
  2. BearerTokenAuthenticationFilter extracts the token; Resource Server support authenticates it using the decoder.
  3. The SecurityConfig converter receives the verified JWT and converts sub to id.
  4. It queries the database account. Missing or disabled accounts fail with 401.
  5. It builds JwtAuthenticationToken with ROLE_USER or ROLE_ADMIN using the account's current role.
  6. Spring evaluates route rules and, when satisfied, proceeds to the controller.

The role claim describes the role when issued. This application does not treat it as authoritative: it queries the current role for every authentication. A role change therefore affects the next request using an earlier token. /me queries the profile again through the service: there is no guarantee of one SQL query per request.

JWT integration uses Resource Server, even though the lab issues its own JWTs. It does not implement a complete OAuth2 authorisation server, social login or OpenID Connect. Reference for the infrastructure used: JWT in Spring Security.

Authorisation: checking what you may do

text
POST /api/auth/login     → permitAll
POST /api/auth/register  → permitAll
/api/users               → hasRole("ADMIN")
/api/users/**            → hasRole("ADMIN")
cualquier otra petición → authenticated

The table shows matcher order and actual scope. PermitAll applies only to the two POST routes, not all of /api/auth. The entity stores ADMIN; Spring compares authority ROLE_ADMIN when using hasRole("ADMIN"). Even on a public route, an invalid supplied token can be rejected by the Bearer filter: public means credentials are not required.

The React guard hides or redirects screens to simplify navigation. Actual protection is in Spring: an HTTP client can call routes without going through React.

STATELESS, CSRF and CORS

STATELESS avoids persisting authentication in an HTTP session. Every request resends and validates its JWT and, here, also queries MySQL. It does not mean the application or database has no state. formLogin and httpBasic are disabled in favour of JSON API and Bearer authentication.

CSRF is disabled because the credential is explicitly sent in Authorization, rather than an authentication cookie automatically attached by the browser. Review CSRF if changing to cookies. CORS limits which browser origins may read responses: it accepts FRONTEND_URL origins, GET/POST/PUT/DELETE/OPTIONS methods and Authorization/Content-Type headers. CORS neither replaces authentication nor blocks clients such as curl.

React session and cache

AuthContext keeps user and expiresAt in React state; api.js keeps the token in a module variable. localStorage is not used. A timer logs out on expiresIn; a 401 from an authenticated request also calls logout. A 403 reports insufficient permissions without automatically ending the session.

TanStack Query manages remote queries. Key ['me'] queries the current profile and refetches on focus according to its default behaviour. UsersPage uses ['users']; saving invalidates users and me, deletion invalidates users. Login/logout clear the cache to avoid showing another account's data. Search is computed in memory over users.data.

What really invalidates a token

ActionResult with an earlier unexpired token
Logout in ReactIt is removed locally. A copy of the token remains valid.
Reload the browserThe local token is lost; it is not revoked on the server.
Change passwordLogin requires the new password; the previous token remains valid.
Change roleNew authorities apply on the token's next use.
Disable / delete accountActive-account lookup fails: 401.
Reactivate accountIts unexpired tokens become usable again.
Change JWT_SECRET and restartTokens signed with the previous secret fail verification.
Reach expThe token expires; a new login is required.

Extensions for further learning

The project has no logout endpoint or revocation list. Revoking individual sessions would require additional state, such as sessions or credential versions. There are no refresh tokens: renewal requires login. Further exercises include pagination, credential rate limiting, email verification and password recovery; do not confuse these with implemented features.

CV & portfolio · ES / EN
EspañolEnglish