I have the following Spring Security configuration:
httpSecurity .csrf().disable() .exceptionHandling() .authenticationEntryPoint(unauthorizedHandler) .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/**").fullyAuthenticated() .and() .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:
@Override public void configure(WebSecurity webSecurity) { webSecurity.ignoring().antMatchers("/some_endpoint"); }
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?
Spring security provides few options to register the custom filter. We can use one of them based on our requirement. addFilterAfter(filter, class)–Adds a filter after the position of the specified filter class. addFilterBefore(filter, class)–Filter before the position of the specified filter class.
Spring Security's web infrastructure is based entirely on standard servlet filters. It doesn't use servlets or any other servlet-based frameworks (such as Spring MVC) internally, so it has no strong links to any particular web technology.
Class AuthenticationFilterA Filter that performs authentication of a particular request. An outline of the logic: A request comes in and if it does not match setRequestMatcher(RequestMatcher) , then this filter does nothing and the FilterChain is continued.
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:
http .antMatcher("/api/**") .authorizeRequests() // .anyRequest().authenticated() // .and() .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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With