Reputation: 4914
I'm building a RESTful server, and I need to apply a custom filter to some paths but not others, but I'm doing something wrong. Here's my Security configuration class:
@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
private final CustomFilter customFilter;
@Autowired
public AppSecurityConfig(CustomFilter filter) { customFilter = filter; }
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/auth/user/**")
.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
}
}
According to what I've read, the filter will be applied to any path starting with /auth/user
, but not with, say, /auth/admin
. But my filter logging is telling me that the filter gets applied to any request I make.
I don't have to worry about authentication because my server will only be visible to a single back-end application, which needs a secret key to connect. But I need this filter to work properly.
Addendum: I've added the annotations on the class for clarity. I should also mention that the filter extends OncePerRequestFilter:
@Component
public class CustomFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(CustomFilter.class);
@Override
protected void doFilterInternal(
final HttpServletRequest request,
final HttpServletResponse response,
final FilterChain filterChain
) throws ServletException, IOException {
log.trace("Executing CustomFilter");
filterChain.doFilter(request, response);
}
}
Upvotes: 1
Views: 4087
Reputation: 6248
Your filter is being applied to every request because it is probably a bean (annotated with @Component
).
When you register a Filter
as a bean, Spring Boot picks it up automatically and put it into the filter chain, note that this is not the Spring Security's SecurityFilterChain
.
To avoid that, do not register your custom filter as a bean, just make it a regular Java object and register via .addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
, this way the Filter
will only be present inside the SecurityFilterChain
.
Upvotes: 2