Search code examples
javaspringspring-bootspring-security

Java Spring requestMatchers permit paths within authenticated path


I am trying to protect all paths at /admin/** but allow /admin/auth/** for the login.

I have tried this but does not work;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((requests) -> requests
                        .requestMatchers("/admin/**").authenticated()
                        .requestMatchers("/admin/auth/**").permitAll()
                        .anyRequest().permitAll()
                );
        // Disable csrf for now
        http.csrf(c -> c.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).ignoringRequestMatchers("admin/**"));
        http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

How can I change it?


Solution

  • The fine-grained request pattern should be applied first.

    with the broader scope pattern filtered out first if it's above it

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((requests) -> requests
                        .requestMatchers("/admin/auth/**").permitAll()
                        .requestMatchers("/admin/**").authenticated()
                        .anyRequest().permitAll()
                );
        // Disable csrf for now
        http.csrf(c -> c.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).ignoringRequestMatchers("admin/**"));
        http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }