I need to use autwired in a filter. So I annotate my filter class using @Component,
import org.springframework.web.filter.GenericFilterBean; @Component public class TokenAuthorizationFilter extends GenericFilterBean { @Autowired public EnrollCashRepository enrollCashRepository; }
Then I add my filter as shown below in SecurityConfig,
@Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(WebSecurity webSecurity) throws Exception { webSecurity.ignoring().antMatchers(HttpMethod.GET, "/health"); } @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(new TokenAuthorizationFilter(), BasicAuthenticationFilter.class); http.authorizeRequests().antMatchers("/api/**").authenticated(); }
My problem is that my filter is called twice using the @Component annotation. If I delete the @Component annotation, it will be called only once.
Then I add below as a fix to my main Spring boot class. Then I will comment on the addFilterBefore line in SecurityConfig.
@Bean public FilterRegistrationBean tokenAuthFilterRegistration() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new PITokenAuthorizationFilter()); filterRegistrationBean.setOrder(1); filterRegistrationBean.setEnabled(false); return filterRegistrationBean; }
But then my filter is called once. But even I make setEnabled true or false, I get Forbiddon 403 error when I call my rest api, http: // localhost: 8080 / api / myservice
How can I fix this situation when I can use @Autowired in my Spring Filter?
Edit: add controller and filter class,
@RestController @RequestMapping(value = "/api") public class SpringToolController { @RequestMapping(value = "/myservice", method = RequestMethod.GET) public HttpEntity<String> myService() { System.out.println("-----------myService invoke-----------"); return new ResponseEntity<String>(HttpStatus.OK); } } public class TokenAuthorizationFilter extends GenericFilterBean { public TokenAuthorizationFilter(EnrollCashRepository enrollCashRepository) { this.enrollCashRepository = enrollCashRepository; } public EnrollCashRepository enrollCashRepository; @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { System.out.println("before PITokenAuthorizationFilter"); chain.doFilter(servletRequest, servletResponse); System.out.println("after PITokenAuthorizationFilter"); } public EnrollCashRepository getEnrollCashRepository() { return enrollCashRepository; } public void setEnrollCashRepository(EnrollCashRepository enrollCashRepository) { this.enrollCashRepository = enrollCashRepository; } }