Securing a REST API is a layered process covering transport encryption, authentication, authorization, and input handling, each addressing a different class of attack rather than any single control being sufficient on its own.
An API first forces all traffic over HTTPS, requires a valid OAuth2 access token on every request, checks the token's scopes against the requested operation, and validates the request body against a strict schema before processing it.
@Configuration
@EnableMethodSecurity
public class ApiSecurity {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.requiresChannel(c -> c.anyRequest().requiresSecure()) // 1. HTTPS only
.csrf(csrf -> csrf.disable()) // stateless API
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.cors(Customizer.withDefaults()) // 2. allowed origins only
.authorizeHttpRequests(a -> a // 3. authorization rules
.requestMatchers("/actuator/health/**").permitAll()
.requestMatchers(HttpMethod.DELETE, "/api/**").hasAuthority("SCOPE_admin")
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) // 4. validate JWT
.headers(h -> h.contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'none'")))
.build();
}
}
// 5. Validate input -> @Valid DTOs
// 6. Fine-grained checks -> @PreAuthorize on service methods
// 7. Rate limiting -> API gateway (e.g. Spring Cloud Gateway RequestRateLimiter)
// 8. Secrets -> environment variables or a vault, never in codeA concise interview answer is
I'd secure it step by step: HTTPS for encryption in transit, then an authentication mechanism like OAuth2 or JWT to verify identity, then role- or scope-based authorization on each endpoint, and finally input validation to block injection attacks. Logging and rate limiting round it out for visibility and abuse prevention.
Last updated: 11 November 2026
Next question: What is SLF4J logging?