Custom AuthenticationFilter and using permitAll function in spring boot

  Kiến thức lập trình

I am learning spring boot security architecture and for me best way to learn is to try to see how much can I customise it.

Right now I have problem with understanding how to make custom authentication filter.

Let say I have

@Bean
@Order(2)
public SecurityFilterChain generalFilterChain(HttpSecurity http) throws Exception {
    JwtTokenAuthenticationFilter generalFilterChainForAllApiRequests = jwtTokenAuthenticationFilter();
    generalFilterChainForAllApiRequests.setAuthenticationManager(authenticationManager);

    return http.securityMatcher("/api/v1/**")
            .csrf(Customizer.withDefaults())
            .authenticationManager(authenticationManager)
            .authorizeHttpRequests(r -> {
                r.requestMatchers(
                        new RegexRequestMatcher("/api/v1/test/hola", null)).permitAll();
            })
            .addFilterAfter(generalFilterChainForAllApiRequests,UsernamePasswordAuthenticationFilter.class)
            .build();
}



public JwtTokenAuthenticationFilter jwtTokenAuthenticationFilter() {
    JwtTokenAuthenticationFilter filter = new JwtTokenAuthenticationFilter(APPLICATION_GENERAL_PATH);
    filter.setAuthenticationManager(authenticationManager);
    return filter;
}

I understand that my JwtTokenAuthenticationFilter must not be Bean, otherwise it will be applied to all SecurityFilterChains, but I only want to use it on this one ‘generalFilterChain’.

My problem is that I have added that my /api/v1/test/hola is permitted. As I understand it my custom filter should not be called, but it is and this end point is unauthorised.
What I am doing wrong, conceptually and is it possible to have this kinda solution, to have custom filter that can be applied to some end points

LEAVE A COMMENT