Spring Security secures Spring applications by authenticating users, authorizing access, and protecting documents, tools, and premium content from unauthorized use. section 10.0 section 10.1.2
A typical implementation grows in three steps:
- Add the Spring Security starter dependency to the application build. section 10.1.2
- Create a SecurityConfig class with @Configuration and @EnableWebSecurity, then define a SecurityFilterChain and UserDetailsService. section 10.1.2
- Enable method security and use @PreAuthorize with hasRole('PREMIUM_USER') to protect tool methods or Function implementations. section 10.2
Restricting a game-complexity tool
Annotate the @Tool method with @PreAuthorize("hasRole('PREMIUM_USER')"). An authorized request returns the game's complexity; an unauthorized request receives a reserved-for-premium-users response instead of invoking the method.
Listing 10.2 Authenticating users and filtering premium content
package com.example.boardgamebuddy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.
HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.
EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.
AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity #1
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) #2
throws Exception {
http
.httpBasic(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorizeRequests ->
authorizeRequests
.anyRequest().authenticated());
return http.build();
}
@Bean
UserDetailsService userDetailsService() { #3
var user1 = User.builder()
.username("mickey")
.password("{noop}password")
.roles("USER", "PREMIUM_USER")
.build();
var user2 = User.builder()
.username("donald")
.password("{noop}password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user1, user2);
}
}
Inspect the complete Java configuration for authenticating users and filtering premium content. section 10.1.2



