Skip to content

How to apply Spring Security filter only on secured endpoints?

I have the following Spring Security configuration:

        .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

The authenticationTokenFilterBean() is applied even on endpoints that do not match /api/** expression. I also tried adding the following configuration code:

public void configure(WebSecurity webSecurity) {

but this still did not solve my problem. How can I tell Spring Security to apply filters only on endpoints that match the secured URI expression?



I have an application with the same requirement and to solve it I basically restricted Spring Security to a given ant match patter (using antMatcher) as follows:

    .authorizeRequests() //
        .anyRequest().authenticated() //
    .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

You can read it as follows: for http only invoke these configurations on requests matching the ant pattern /api/** authorizing any request to authenticated users and add filter authenticationTokenFilterBean() before UsernamePasswordAuthenticationFilter. For all others requests this configuration has no effect.

User contributions licensed under: CC BY-SA
9 People found this is helpful