Sub topic 2
Users, Password Hashing, and Stateless API Authorization
Assume you know Spring Boot dependency injection, REST controllers, HTTP status codes, and the basic difference between tokens and passwords. This chapter uses an in-memory user for demonstration.
Users and password hashing
A UserDetailsService loads user information during authentication. A PasswordEncoder hashes passwords before storage and checks a login password against its hash. Never store plain-text passwords.
@Configuration
@EnableWebSecurity
class SecurityConfig {
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
var alice = User.withUsername("alice")
.password(encoder.encode("change-me"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(alice);
}
}BCryptPasswordEncoder includes a salt, so equal passwords do not produce one reusable hash. In production, replace the in-memory service with a database-backed UserDetailsService.
Stateless sessions and request authorization
A stateless API does not store a user’s authentication in an HTTP session. Each request carries its credentials, such as an HTTP Basic header or a bearer token.
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/orders/**")
.hasAnyRole("USER", "ADMIN")
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}hasRole("ADMIN") checks for the authority ROLE_ADMIN. hasAuthority("orders.read") checks the exact authority name. Put specific matchers before broad matchers, and test the resulting rules.
CSRF decisions
Cross-Site Request Forgery, or CSRF, tricks a browser into sending an unwanted request with its automatically attached cookie. Keep CSRF protection when authentication uses cookies, especially for browser sessions. For a stateless API using an Authorization header that JavaScript or a client explicitly sends, disabling CSRF is usually appropriate. This decision depends on how credentials are transported, not simply on whether the application is called an API.
Exercise
What authority does hasRole("USER") require, and when should an API keep CSRF enabled?
Show answer
It requires ROLE_USER. Keep CSRF enabled when credentials use browser-managed cookies.