Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use @Autowired with a Filter configured in SpringBoot

I need to use autowired 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 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 my filter get invoked twice with the @Component annotation. If i remove the @Component annotation it only invoke once.

Then i add below as a fix in my Spring boot main class. Then i comment the line of addFilterBefore 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 get invoked once. But even i make the setEnabled true or false, i get a 403 Forbiddon Error when i invoke my rest api, http://localhost:8080/api/myservice

How can i fix this situation where 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;
    }

}
like image 374
Harshana Avatar asked Nov 05 '15 05:11

Harshana


Video Answer


1 Answers

Remove your FilterRegistrationBean and initialize TokenAuthorizationFilter inside your SecurityConfig like this:

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public EnrollCashRepository enrollCashRepository;

    @Override
    public void configure(WebSecurity webSecurity) throws Exception
    {
        webSecurity.ignoring().antMatchers(HttpMethod.GET, "/health");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception 
    {
        http.addFilterBefore(tokenAuthorizationFilter(), BasicAuthenticationFilter.class);  
        http.authorizeRequests().antMatchers("/api/**").authenticated();    
    }

    private TokenAuthorizationFilter tokenAuthorizationFilter() 
    {
        return new TokenAuthorizationFilter(enrollCashRepository);
    }
}

Remove @Autowired and @Component annotation and set your EnrollCashRepository with constructor injection:

import org.springframework.web.filter.GenericFilterBean;

public class TokenAuthorizationFilter extends GenericFilterBean {

    private final EnrollCashRepository enrollCashRepository;

    public TokenAuthorizationFilter(EnrollCashRepository enrollCashRepository) 
    {
        this.enrollCashRepository = enrollCashRepository
    }
}
like image 52
ksokol Avatar answered Sep 21 '22 07:09

ksokol