无法在Spring Boot 2应用程序中为添加拦截器配置WebMvcConfigurer

时间:2019-05-19 08:44:28

标签: spring-boot spring-mvc

我试图在我的spring boot应用程序中第一次创建一个拦截器,但是由于教程中的描述,它以某种方式不会自动创建。

我尝试创建一个WebConfig类,该类扩展了WebMvcConfigurerAdapter类,并将其注释为@Component,但没有用。我还尝试创建一个使用@Configuration和@EnableWebMvc注释实现WebMvcConfigurer接口的WebConfig,但是它也没有起作用。

当前的WebConfig类:

@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);
    }

}

应用程序类

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

    public static void main(String[] args) {

        SpringApplication.run(CoreRestAPIApplication.class, args);

    }
}

我的拦截器类:

@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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

经过一些搜索,我发现我已经注册了WebMvcConfigurationSupport配置。但是,如果有人在寻找并希望使用拦截器修改标头,则请勿为此使用拦截器,因为对于Spring,如果您返回ResponseEntity或控制器方法返回@,它将无法很好地处理它ResponseBody。 相反(至少对于我来说,每次接收到有效请求时,它都会过滤并更新令牌)使用doFilterInternal方法将标头添加到响应中(如果需要,也可以添加cookie。)这是一个示例我做到了:

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);
  }

}