Been self learning Spring Security for a while, and I am now kind of stuck in filter chain. Let's say I have a StaticKeyAuthenticationFilter class, marked with @Component, implements Filter, and has @Value("${authorization.key}"), so that it can read the key value from the yml file.
@Component
public class StaticKeyAuthenticationFilter implements Filter {
@Value("${authorization.key}")
private String authorizationKey;
private final Logger logger = Logger.getLogger(StaticKeyAuthenticationFilter.class.getName());
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
String cAuthentication = httpRequest.getHeader("Cauthorization");
if(authorizationKey.equals(cAuthentication)) {
filterChain.doFilter(httpRequest, httpResponse);
}
else {
logger.info("No cAuthentication in request's header...");
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
And in the SecurityFilterChain class:
@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.httpBasic(Customizer.withDefaults());
return http.build();
}
}
Clearly I am not including the StaticKeyAuthenticationFilter, but from what I see in the log, it's still somehow registered in the filterchain:
2025-01-30T14:17:41.042+08:00 INFO 18884 --- [Book_Store_Blog] [ main] c.e.B.BookStoreBlogApplication : helloController
2025-01-30T14:17:41.042+08:00 INFO 18884 --- [Book_Store_Blog] [ main] c.e.B.BookStoreBlogApplication : staticKeyAuthenticationFilter
2025-01-30T14:17:41.042+08:00 INFO 18884 --- [Book_Store_Blog] [ main] c.e.B.BookStoreBlogApplication : customerService
2025-01-30T14:17:41.042+08:00 INFO 18884 --- [Book_Store_Blog] [ main] c.e.B.BookStoreBlogApplication : com.example.Book_Store_Blog.BookStoreBlogApplication$FindAllCustomer
2025-01-30T14:17:41.042+08:00 INFO 18884 --- [Book_Store_Blog] [ main] c.e.B.BookStoreBlogApplication : passwordEncoder
2025-01-30T14:17:41.042+08:00 INFO 18884 --- [Book_Store_Blog] [ main] c.e.B.BookStoreBlogApplication : authenticationProvider
My assumption would be that it's always in the filter chain because it's marked @Component (I think I need the @Component, otherwise the @Value("${authorization.key}") won't work)
How can I dynamically exclude the StaticKeyAuthenticationFilter from the filter chain instead of commenting out the logic inside the filter?
All I can think of is to remove the @Component annotation or comment out the logic inside of the filter, but it's not dynamic.
I also tried FilterRegistrationBean, but when I say staticKeyAuthenticationBean().setEnabled(false), it always gives me the 'fails to construct StaticKeyAuthenticationFilter bean' error.