我使用Spring安全性与OAuth2(版本:4.0.4.RELEASE)和spring(版本:4.3.1.RELEASE)。
我正在开发Angular的前端,而我正在使用grunt connect:dev(http://127.0.0.1:9000)。当我尝试通过localhost地址登录时,一切正常,但我从其他地方收到错误:
" XMLHttpRequest无法加载http://localhost:8084/oauth/token?client_id=MY_CLIENT_ID。对预检请求的响应没有通过访问控制检查:否'访问控制 - 允许 - 来源'标头出现在请求的资源上。起源' http://127.0.0.1:9000'因此不允许访问。响应具有HTTP状态代码401。"
我已在WebMvcConfigurerAdapter(如下所示)中配置了映射(Overrided public void addCorsMappings(CorsRegistry registry)),但它仍然不适用于http://127.0.0.1:9000。
registry.addMapping("/**")
.allowedOrigins("http://127.0.0.1:9000")
.allowedMethods("POST", "OPTIONS", "GET", "DELETE", "PUT")
.allowedHeaders("X-Requested-With,Origin,Content-Type,Accept,Authorization")
.allowCredentials(true).maxAge(3600);
配置基于:https://spring.io/guides/gs/rest-service-cors/
请指出解决此问题的正确方法。
答案 0 :(得分:13)
希望你很久以前找到答案,但如果没有(如果其他人发现这个问题就像我一样):
问题是Spring Security使用过滤器,这些过滤器通常优先于用户定义的过滤器,@CrossOrigin
和类似的注释等。
对我来说有用的是将CORS过滤器定义为具有最高优先级的bean,如建议的here。
@Configuration
public class MyConfiguration {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://127.0.0.1:9000");
config.setAllowedMethods(Arrays.asList("POST", "OPTIONS", "GET", "DELETE", "PUT"));
config.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}
答案 1 :(得分:1)
抱歉,响应时间长。我通过如下配置我的CORS过滤器解决了该问题:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {
private static final Logger LOGGER = LogManager.getLogger(CORSFilter.class.getName());
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
final String origin = ((HttpServletRequest) req).getHeader("Origin");
if (ofNullable(origin).isPresent() && origin.equals("http://127.0.0.1:9000")) {
LOGGER.info("CORSFilter run");
response.addHeader("Access-Control-Allow-Origin", "http://127.0.0.1:9000");
response.addHeader("Access-Control-Allow-Credentials", "true");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type,Accept,Authorization");
response.setStatus(200);
}
}
chain.doFilter(addNessesaryHeaders(request), response);
}
private MutableHttpServletRequest addNessesaryHeaders(final HttpServletRequest request) {
final MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
mutableRequest.putHeader("Accept", "application/json");
mutableRequest.putHeader("Authorization", "Basic" + " bXVzaWNzY2hvb2w6");
return mutableRequest;
}
@Override
public void destroy() {
}
}
答案 2 :(得分:0)
你可以尝试类似的东西
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods(HttpMethod.OPTIONS.name(),
HttpMethod.PATCH.name(),
HttpMethod.PUT.name(),
HttpMethod.DELETE.name(),
HttpMethod.GET.name(),
HttpMethod.POST.name())
.maxAge(360);
}
};
}
}
注意:Spring版本应为4.2或更高版本
答案 3 :(得分:0)
以下为我工作。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}