Home > OS >  Unable to inject bean in OncePerRequestFilter
Unable to inject bean in OncePerRequestFilter

Time:04-10

I'm not being able to inject beans into my OncePerRequestFilter. Here's the XHeaderAuthenticationFilter:


@Component
public class XHeaderAuthenticationFilter extends OncePerRequestFilter {

  public XHeaderAuthenticationFilter() {
    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
  }

  @Autowired private JwtUtils jwtUtils; // null
  @Autowired private UserService userService; // null

  @Override
  @SneakyThrows
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {

    String path = request.getRequestURI();
    if (new AntPathMatcher().match("/getToken", path)
        || HttpMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod())) {
      filterChain.doFilter(request, response);
      return;
    }

    String jwt = parseJwt(request);
    jwtUtils.validateJwtToken(jwt); // NullPointerException here

    // ...

    filterChain.doFilter(request, response);
  }
}

And here the registration part:

  @Bean
  public FilterRegistrationBean filterRegistrationBean() {
    FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(new XHeaderAuthenticationFilter());
    registrationBean.setEnabled(false);
    return registrationBean;
  }

I set enabled to false as the filter was getting called multiple times. I'm new to SpringSecurity and need much exposure to the concept. I also want to add the configuration part just in case I did something wrong there:

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.cors()
        .and()
        .csrf()
        .disable()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        .antMatchers("/getToken")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .exceptionHandling()
        .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
        .and()
        .addFilterBefore(
            new XHeaderAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
  }

There are a lot of fixes for this issue but none worked for me. I don't know where I'm going wrong.

Update 1

Including JwtUtils:

@Component
public class JwtUtils {

  @Value("${security.jwtSecret}")
  private String jwtSecret;

  @Value("${security.jwtExpirationMs}")
  private int jwtExpirationMs;

  public String getJWTToken(String username) {}

  public boolean validateJwtToken(String authToken) {}

  public Claims getAllClaimsFromToken(String token) {}
}

and UserService:

@Service
public class UserServiceImpl implements UserService {

  @Autowired private UserRepository userRepository;

  @Override
  public User saveUser(UserModel userModel) {}

  @Override
  public UserModel findUserByEmail(String email) {}

  @Override
  public UserListViewResponse findAllUsers(Specification<User> userSpecification, Pageable paging) {}

  @Override
  public UserModel deleteUser(String email) {}

  private UserListViewResponse populateUserListViewResponse(Page<User> pagedResult) {}

  private List<User> filterAdmins(List<User> userEntityList) {}

CodePudding user response:

The way you register XHeaderAuthenticationFilter in FilterRegistrationBean causes the problem because you yourself create the XHeaderAuthenticationFilter with new not Spring with all resolving DI stuff. change your code like:

@Autowired
XHeaderAuthenticationFilter xHeaderAuthenticationFilter;

@Bean
public FilterRegistrationBean filterRegistrationBean() {
    FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(xHeaderAuthenticationFilter);
    return registrationBean;
}

Same applies if you want to register XHeaderAuthenticationFilter using addFilterBefore

  • Related