GoCruze is a ride-booking backend for working parents, so its API handles children's school commutes. For an app like that, security can't be an afterthought. It shapes the design: who is calling, what are they allowed to do, and how do you prove the rules work?
This post walks through the approach I learned: stateless JWT authentication with Spring Security 6, role-based access control (RBAC) for three roles, and JUnit 5 tests for the security rules. The roles here (PARENT, DRIVER, ADMIN) are examples to keep the code concrete.
Authentication vs authorization
Two words that are easy to mix up:
Authentication: who are you? (log in, prove identity)
Authorization: what may you do? (roles, ownership, permissions)
Spring Security handles both through a chain of servlet filters that every request passes through before it reaches your controller.
Request + Bearer token↓→
Security filter chain↓→
JWT validated → SecurityContext↓→
URL + method rules↓→
Controller
If any step fails, the request never reaches the controller: 401 for 'who are you?', 403 for 'not allowed'.
Why JWT for a REST API
A classic web app keeps a session on the server and gives the browser a cookie. That works, but every server instance needs access to the session store.
A JSON Web Token carries the identity inside the token itself:
The header says how it's signed (for example HS256).
The payload holds claims: subject (user), roles, issue time, expiry.
The signature proves the token was issued by us and not modified.
Because the server only needs the signing key to verify a token, the API is stateless. Any instance can handle any request, which makes scaling out simple.
Use what Spring Security already gives you
It's tempting to write a custom OncePerRequestFilter that parses the token by hand, and many tutorials do. But Spring Security ships a complete, tested implementation: the OAuth 2.0 Resource Server support. It reads the Authorization: Bearer header, verifies the signature and expiry, and builds the Authentication for you.
@Configuration@EnableMethodSecurity // enables @PreAuthorize on service/controller methodspublic class SecurityConfig { @Bean SecurityFilterChain api(HttpSecurity http) throws Exception { http // no cookies → no CSRF risk for this stateless API .csrf(csrf -> csrf.disable()) .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth .requestMatchers("/api/auth/**").permitAll() .requestMatchers("/api/admin/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/api/bookings/**").hasRole("PARENT") .requestMatchers("/api/trips/**").hasAnyRole("DRIVER", "ADMIN") .anyRequest().authenticated()) .oauth2ResourceServer(oauth -> oauth .jwt(jwt -> jwt.jwtAuthenticationConverter(rolesFromJwt()))); return http.build(); } /** Turns the token's "roles" claim ["PARENT"] into authorities [ROLE_PARENT]. */ private JwtAuthenticationConverter rolesFromJwt() { var authorities = new JwtGrantedAuthoritiesConverter(); authorities.setAuthoritiesClaimName("roles"); authorities.setAuthorityPrefix("ROLE_"); var converter = new JwtAuthenticationConverter(); converter.setJwtGrantedAuthoritiesConverter(authorities); return converter; } @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); // slow on purpose: hard to brute-force } @Bean AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception { // built by Spring Boot from our UserDetailsService + PasswordEncoder beans return config.getAuthenticationManager(); }}
Rules are checked top to bottom, first match wins, so specific paths go before general ones and anyRequest() comes last.
Signing and verifying tokens
For a single API that issues and checks its own tokens, a symmetric HMAC key (HS256) is enough. The key must be at least 256 bits and must come from the environment, never from the code:
java
@Configurationclass JwtConfig { @Bean SecretKey jwtKey(@Value("${app.jwt.secret}") String secret) { // app.jwt.secret is set from an environment variable, min. 32 bytes return new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); } @Bean JwtDecoder jwtDecoder(SecretKey jwtKey) { return NimbusJwtDecoder.withSecretKey(jwtKey).build(); // checks signature + expiry } @Bean JwtEncoder jwtEncoder(SecretKey jwtKey) { return new NimbusJwtEncoder(new ImmutableSecret<>(jwtKey)); }}