Chapter 04

Authentication and roles

Three roles, one filter chain, and a rule that is worth repeating: the front end decides what to show, the back end decides what is allowed. Only one of those is security.

⏱ 18 min readLevel: intermediateHands-on

The permission model

CapabilityVIEWEROPERATORADMIN
Search and read orders✔✔✔
Create and edit drafts—✔✔
Place, pay, fulfil, deliver—✔✔
Cancel—✔✔
Refund——✔
Manage users and products——✔

Users in the database

db/migration/V4__users.sql
CREATE TABLE app_user (
    user_id       bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email         citext      NOT NULL UNIQUE,
    password_hash text        NOT NULL,
    display_name  text        NOT NULL,
    enabled       boolean     NOT NULL DEFAULT true,
    created_at    timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE user_role (
    user_id bigint NOT NULL REFERENCES app_user ON DELETE CASCADE,
    role    text   NOT NULL CHECK (role IN ('VIEWER','OPERATOR','ADMIN')),
    PRIMARY KEY (user_id, role)
);
Store a hash, never a password

password_hash holds a BCrypt (or Argon2) digest. Never log it, never return it in a DTO, and never compare with equals — use PasswordEncoder.matches, which is constant-time.

The filter chain

security/SecurityConfig.java
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http, JwtAuthFilter jwtFilter) throws Exception {
        return http
            // stateless JWT API: no session for CSRF to protect
            .csrf(AbstractHttpConfigurer::disable)
            .cors(Customizer.withDefaults())
            .sessionManagement(s -> s.sessionCreationPolicy(STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/auth/login", "/actuator/health/**").permitAll()
                .requestMatchers(HttpMethod.GET, "/api/**").hasAnyRole("VIEWER","OPERATOR","ADMIN")
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .requestMatchers("/actuator/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
            .exceptionHandling(e -> e
                .authenticationEntryPoint(new ProblemDetailEntryPoint())
                .accessDeniedHandler(new ProblemDetailAccessDeniedHandler()))
            .headers(h -> h
                .contentSecurityPolicy(c -> c.policyDirectives("default-src 'none'"))
                .frameOptions(FrameOptionsConfig::deny))
            .build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource(
            @Value("${app.cors.allowed-origins}") List<String> origins) {
        CorsConfiguration c = new CorsConfiguration();
        c.setAllowedOrigins(origins);              // explicit, never "*" with credentials
        c.setAllowedMethods(List.of("GET","POST","PUT","DELETE","OPTIONS"));
        c.setAllowedHeaders(List.of("Authorization","Content-Type"));
        c.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/api/**", c);
        return source;
    }
}
Disabling CSRF is only safe here because of two facts

The API is stateless and the token travels in an Authorization header, not a cookie. A browser does not attach headers to a cross-site request automatically, so there is nothing for an attacker to ride. The moment you move the token into a cookie, CSRF protection comes back.

Issuing and validating tokens

security/TokenService.java
@Service
public class TokenService {

    private final JwtEncoder encoder;
    private final Duration ttl;

    public String issue(AppUser user) {
        Instant now = Instant.now();
        JwtClaimsSet claims = JwtClaimsSet.builder()
            .issuer("bitsnippets-oms")
            .issuedAt(now)
            .expiresAt(now.plus(ttl))
            .subject(user.email())
            .claim("uid",   user.id())
            .claim("name",  user.displayName())
            .claim("roles", user.roles())          // ["OPERATOR"]
            .build();
        return encoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
    }
}
security/AuthController.java
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @PostMapping("/login")
    public LoginResponse login(@Valid @RequestBody LoginRequest req) {
        AppUser user = users.findByEmail(req.email())
            .filter(u -> u.enabled())
            .filter(u -> encoder.matches(req.password(), u.passwordHash()))
            .orElseThrow(() -> new BadCredentialsException("Invalid email or password."));

        return new LoginResponse(tokens.issue(user), user.displayName(), user.roles());
    }

    @GetMapping("/me")
    public MeResponse me(Authentication auth) {
        return MeResponse.from(auth);
    }
}
One error message for both failures

"Invalid email or password" whether the account is missing or the password is wrong. Distinguishing them hands an attacker a free account-enumeration oracle. Rate-limit the endpoint too — five attempts per minute per IP is plenty for humans.

application.yml
app:
  jwt:
    ttl: PT8H
    # RSA keys mounted as files; never committed, never in the image
    public-key:  ${JWT_PUBLIC_KEY_PATH:classpath:dev-public.pem}
    private-key: ${JWT_PRIVATE_KEY_PATH:classpath:dev-private.pem}
  cors:
    allowed-origins: https://oms.bitsnippets.com

Method security for the fine-grained rules

order/OrderService.java
@PreAuthorize("hasAnyRole('OPERATOR','ADMIN')")
@Transactional
public Order create(CreateOrderRequest req, String actor) { … }

// refunds move money — admin only, expressed where the rule lives
@PreAuthorize("(#target.name() == 'REFUNDED') ? hasRole('ADMIN') " +
              ": hasAnyRole('OPERATOR','ADMIN')")
@Transactional
public Order transition(long id, OrderStatus target, int expectedVersion, String actor) { … }
URL rules and method rules do different jobs

The filter chain gives coarse protection at the edge — cheap, and it catches paths you forgot to annotate. Method security sits next to the business rule so it cannot be bypassed by a scheduled job or a second controller calling the same service. Use both.

Who did it — the audit actor

the actor recorded in order_event comes from the token, never the request body
@Component
public class CurrentUser {
    public String email() {
        Authentication a = SecurityContextHolder.getContext().getAuthentication();
        if (a == null || !a.isAuthenticated()) {
            throw new IllegalStateException("No authenticated user in context.");
        }
        return a.getName();
    }
}

If a client could send "actor": "someone.else@example.com", the audit trail would be fiction.

Test every role against every endpoint

SecurityMatrixTest.java
@SpringBootTest
@AutoConfigureMockMvc
class SecurityMatrixTest {

    @Autowired MockMvc mvc;

    static Stream<Arguments> matrix() {
        return Stream.of(
            arguments("VIEWER",   "GET",  "/api/orders",              200),
            arguments("VIEWER",   "POST", "/api/orders",              403),
            arguments("OPERATOR", "POST", "/api/orders",              201),
            arguments("OPERATOR", "GET",  "/api/admin/users",         403),
            arguments("ADMIN",    "GET",  "/api/admin/users",         200),
            arguments(null,       "GET",  "/api/orders",              401));
    }

    @ParameterizedTest(name = "{0} {1} {2} -> {3}")
    @MethodSource("matrix")
    void enforcesMatrix(String role, String method, String path, int expected)
            throws Exception {
        var request = request(HttpMethod.valueOf(method), path)
                        .contentType(APPLICATION_JSON).content(validBody(path));
        if (role != null) request = request.with(user("u").roles(role));

        mvc.perform(request).andExpect(status().is(expected));
    }
}
This test is the cheapest security you will ever write

A parameterised matrix catches the single most common real-world failure: a new endpoint merged without an authorisation rule. Add a row whenever you add an endpoint, and a missing @PreAuthorize fails the build instead of the pen test.

The Angular app hides the "Refund" button for operators. Is that sufficient?

Client-side checks are a usability feature. curl, the browser console and a replayed request all ignore them. The @PreAuthorize on transition is what actually stops the refund.