Search code examples
javaspringsecuritymodel-view-controllerroles

Spring security configuration SecurityFilterChain defaultSecurityFilterChain permitAll problem


If inside @Bean SecurityFilterChain defaultSecurityFilterChain build http chain with .requestMatchers("/auth/**").permitAll(); controller with mapping "/auth" cannot be invoked due to 403 but if I use requestMatchers("/**").permitAll() I can proceed to that address. Why it is so?

@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
    http.cors().disable().csrf().disable()
            .authorizeHttpRequests()
            /*.requestMatchers("/myAccount").hasAuthority("VIEWACCOUNT")
            .requestMatchers("/myBalance").hasAnyAuthority("VIEWACCOUNT","VIEWBALANCE")
            .requestMatchers("/myLoans").hasAuthority("VIEWLOANS")
            .requestMatchers("/myCards").hasAuthority("VIEWCARDS")*/
            .requestMatchers("/auth/**").permitAll();


    return http.build();
}

@RestController("/auth") public class LoginController {

@Autowired
private CustomerRepository customerRepository;

@Autowired
private PasswordEncoder passwordEncoder;


@GetMapping
public String showUserString(@RequestBody User user) {
    return "Hello World!";
}`

Solution

  • Implement SecurityConfiguration like this:

    @Bean
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http
            // .csrf().disable not recommended in prod environment
            .csrf().disable()
            .authorizeHttpRequests((authz) -> authz
                .requestMatchers("/auth/**").permitAll()
                .anyRequest().authenticated()
            );
    
            return http.build();
    }
    

    Then change this line

    @RestController("/auth")
    

    to

    @RestController
    @RequestMapping("/auth")
    

    and this line

    @GetMapping
    

    to

    @RequestMapping(value = "/showUserString", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)