2020@ EnableWebSecurity
2121public class SecurityConfig {
2222
23+ private static final String RANDOM_USERS_PATH = "/random-users/**" ;
24+ private static final String ADMIN_ROLE = "ADMIN" ;
25+
2326 @ Value ("${app.security.admin.username}" )
2427 private String adminUsername ;
2528
@@ -39,35 +42,39 @@ public class SecurityConfig {
3942 private String testPassword ;
4043
4144 @ Bean
42- SecurityFilterChain securityFilterChain (HttpSecurity http ) throws Exception {
43- http
44- .csrf (csrf -> csrf .ignoringRequestMatchers ("/random-users/**" ))
45- .sessionManagement (session -> session .sessionCreationPolicy (SessionCreationPolicy .STATELESS ))
46- .httpBasic (Customizer .withDefaults ())
47- .authorizeHttpRequests (auth -> auth
48- .requestMatchers (
49- "/api/**" ,
50- "/swagger-ui/**" ,
51- "/swagger-ui.html" ,
52- "/v3/api-docs/**" ,
53- "/actuator/health"
54- ).permitAll ()
55- .requestMatchers (HttpMethod .OPTIONS , "/**" ).permitAll ()
56- .requestMatchers (HttpMethod .GET , "/random-users/**" ).hasAnyRole ("ADMIN" , "USER" , "TEST" )
57- .requestMatchers (HttpMethod .POST , "/random-users/**" ).hasRole ("ADMIN" )
58- .requestMatchers (HttpMethod .PUT , "/random-users/**" ).hasRole ("ADMIN" )
59- .requestMatchers (HttpMethod .DELETE , "/random-users/**" ).hasRole ("ADMIN" )
60- .anyRequest ().authenticated ()
61- );
62-
63- return http .build ();
45+ SecurityFilterChain securityFilterChain (HttpSecurity http ) {
46+ try {
47+ http
48+ .csrf (csrf -> csrf .ignoringRequestMatchers (RANDOM_USERS_PATH ))
49+ .sessionManagement (session -> session .sessionCreationPolicy (SessionCreationPolicy .STATELESS ))
50+ .httpBasic (Customizer .withDefaults ())
51+ .authorizeHttpRequests (auth -> auth
52+ .requestMatchers (
53+ "/api/**" ,
54+ "/swagger-ui/**" ,
55+ "/swagger-ui.html" ,
56+ "/v3/api-docs/**" ,
57+ "/actuator/health"
58+ ).permitAll ()
59+ .requestMatchers (HttpMethod .OPTIONS , "/**" ).permitAll ()
60+ .requestMatchers (HttpMethod .GET , RANDOM_USERS_PATH ).hasAnyRole (ADMIN_ROLE , "USER" , "TEST" )
61+ .requestMatchers (HttpMethod .POST , RANDOM_USERS_PATH ).hasRole (ADMIN_ROLE )
62+ .requestMatchers (HttpMethod .PUT , RANDOM_USERS_PATH ).hasRole (ADMIN_ROLE )
63+ .requestMatchers (HttpMethod .DELETE , RANDOM_USERS_PATH ).hasRole (ADMIN_ROLE )
64+ .anyRequest ().authenticated ()
65+ );
66+
67+ return http .build ();
68+ } catch (Exception exception ) {
69+ throw new SecurityConfigurationException ("Failed to build Spring Security filter chain" , exception );
70+ }
6471 }
6572
6673 @ Bean
6774 UserDetailsService userDetailsService (PasswordEncoder passwordEncoder ) {
6875 UserDetails admin = User .withUsername (adminUsername )
6976 .password (passwordEncoder .encode (adminPassword ))
70- .roles ("ADMIN" )
77+ .roles (ADMIN_ROLE )
7178 .build ();
7279
7380 UserDetails user = User .withUsername (userUsername )
0 commit comments