我正在使用 spirng boot 和 security 3.2.3。我注册了一个拦截器来以这种方式处理特定路径:
@EnableWebMvc
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Autowired
private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
log.info("Start registering custom interceptors...");
registry.addInterceptor(jwtTokenAdminInterceptor)
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin/employee/login");
}
}
我以这种方式配置了 Spring Security:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors().configurationSource(corsConfigurationSource()).and()
.authorizeRequests(authorizeRequests ->
authorizeRequests
.anyRequest().permitAll()
)
.csrf().disable();
return http.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*")); // Allow all origins for development
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
它正在开发中,所以我可以访问所有源代码。目前,应用程序启动时我可以看到“开始注册自定义拦截器...”日志。但不幸的是,拦截器,即
JwtTokenAdminInterceptor
永远无法工作。目前拦截器的实现非常简单:
@Component
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
log.info("Interceptor is called.");
return true;
}
}
我在一些教程中看到,他们
@Override
preHandle
但我的不允许我这样做,并给出了“方法不会覆盖其超类中的方法”错误。
请帮忙,谢谢。
我终于注意到
HandlerInterceptor
正在使用jakarta.servlet.http
而不是javax.servlet.http
。有一笔从 Javax 到雅加达的交易。我希望这能有所帮助。