How to deny all requests without specific roles - SpringBoot security config

Viewed 660

I have the following SpringBoot web security configuration. For authorization, I want to automatically forbid all requests that authentication does not include the roles ADMIN, SUPER_ADMIN, CUSTOMER but this denies all requests and only picks up the denyAll attribute in the springExprFilter hence it votes to deny access.

What am I missing from my configuration?

@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  private final MemberDetailsService memberDetailsService;
  private final JwtRequestFilter jwtRequestFilter;

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(memberDetailsService).passwordEncoder(getPasswordEncoder());
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.headers()
        .disable()
        .csrf()
        .disable()
        .authorizeRequests()
        // permit all request for authentication
        .antMatchers("/v1/authenticate")
        .permitAll()
        .and()
        .authorizeRequests()
        // permit all request with the following list of roles
        // methods will enforce their own authorization logic
        .antMatchers("/v1/members/")
        .hasAnyAuthority("ADMIN", "CUSTOMER", "SUPER_ADMIN")
        .and()
        .authorizeRequests()
        .anyRequest()
        .denyAll()
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
  }
1 Answers

I figured out the spring security configuration expression was correct. The issue was that the antmatcher .antMatchers("/v1/members/") was incorrect. It was implying to match a request with the path /v1/members/ which was not the intended functionality.

For any interested party, the request I was making was GET v1/members/:uuid.

I ought to have used a wildcard .antMatchers("/v1/members/**") to catch all request for the member endpoint.

Related