这是我的配置:
@Configuration @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { // @formatter:off registry .addMapping("/**") .allowedOrigins(CrossOrigin.DEFAULT_ORIGINS) .allowedHeaders(CrossOrigin.DEFAULT_ALLOWED_HEADERS) .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .maxAge(3600L); // @formatter:on } ... }
现在,当我尝试访问我的API时,出现以下错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/api/v1.0/user. (Reason: CORS preflight channel did not succeed).
我在做什么错,以及如何正确配置CORS标头以避免发生此问题?
我已经通过创建新的CORS过滤器解决了此问题:
@Component public class CorsFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token"); response.addHeader("Access-Control-Expose-Headers", "xsrf-token"); if ("OPTIONS".equals(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { filterChain.doFilter(request, response); } } }
并将其添加到安全配置中:
.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class)
更新-如今,我使用了更现代的方式切换到:
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .cors() .and() ... } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("*")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "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; } }