Tal Aloni
Tal Aloni

Reputation: 51

Can't configure WebMvcConfigurer for interceptors addition in spring boot 2 application

I am trying to create an interceptor for the first time in my spring boot application, but somehow it is not created automatically, as described in the tutorials.

I've tried to create a WebConfig class that extends the WebMvcConfigurerAdapter class and annotated it as a @Component but it haven't worked. I also tried to create a WebConfig that implements the WebMvcConfigurer interface with @Configuration and @EnableWebMvc annotations but it hadn't worked either.

current WebConfig class:

@Configuration
@EnableWebMvc
@ComponentScan("com.*")
public class WebConfig implements WebMvcConfigurer {


    public WebConfig() {
        super();
    }

    @Autowired
    HandlerInterceptor headerModifierInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("------------------hi");
        registry.addInterceptor(headerModifierInterceptor);
    }

}

Application class

@SpringBootApplication
@EnableWebSecurity
@ComponentScan(basePackages = {"com.*"})
@EntityScan("com")
public class CoreRestAPIApplication {

    public static void main(String[] args) {

        SpringApplication.run(CoreRestAPIApplication.class, args);

    }
}

My interceptor class:

@Component
public class RestTemplateHeaderModifierInterceptor
        implements HandlerInterceptor {

    @Autowired
    AuthUtil authUtil;

    @Autowired
    JwtTokenProvider jwtTokenProvider;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String resolvedToken = jwtTokenProvider.resolveToken(request);
        if (!StringUtils.isEmpty(resolvedToken)) {
            String updatedToken = jwtTokenProvider.createToken(jwtTokenProvider.getUsername(resolvedToken), jwtTokenProvider.getAuthentication(resolvedToken).getAuthorities());
            response.addHeader(authUtil.AUTH_HEADER_NAME, updatedToken);
        }
    }
}

Upvotes: 0

Views: 1774

Answers (1)

Tal Aloni
Tal Aloni

Reputation: 51

After some search, I've found that I have a registered WebMvcConfigurationSupport configuration. However, if someone is looking and wishes to modify headers using an interceptor, DO NOT use an interceptor for that, as for spring will not handle it well if you return a ResponseEntity or your controller method returns a @ResponseBody. Instead(at least for my use which is filtering and renewing a token every time a valid request is received) use the doFilterInternal method to add the header to the response(or add a cookie if you wish..) here is an example of how I did it:

public class JwtTokenFilter extends OncePerRequestFilter {

  private JwtTokenProvider jwtTokenProvider;

  public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {
    this.jwtTokenProvider = jwtTokenProvider;
  }

  @Override
  protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    String token = jwtTokenProvider.resolveToken(httpServletRequest);
    try {
      if (token != null && jwtTokenProvider.validateToken(token)) {
        Authentication auth = jwtTokenProvider.getAuthentication(token);
        SecurityContextHolder.getContext().setAuthentication(auth);
        if(!jwtTokenProvider.isExpired(token)) {
          httpServletResponse.setHeader("authKey", jwtTokenProvider.createToken(jwtTokenProvider.getUsername(token), auth.getAuthorities()));
        }
      }
    } catch (ClientErrorException ex) {
      //this is very important, since it guarantees the models is not authenticated at all
      SecurityContextHolder.clearContext();
      httpServletResponse.sendError(ex.getStatus().value(), ex.getMessage());
      return;
    }

    filterChain.doFilter(httpServletRequest, httpServletResponse);
  }

}

Upvotes: 1

Related Questions