在spring boot 1.5中,配置跨域一般是直接在controller或是在某一个方法上添加 @CrossOrigin 注解即可,如下:
但是升级到spring boot 2.0版本(springframework5.0.2)后,浏览器会报错
查看options请求的响应可以看到Access-Control-Allow-Origin字段为*
这里响应头中Access-Control-Allow-Origin必须为指定的域名,并且如果想要携带cookie信息还需要添加
Access-Control-Allow-Credentials: true
看一下@CrossOrigin源码
springframework4.3.12:
/**
* Whether the browser should include any cookies associated with the
* domain of the request being annotated.
* <p>Set to {@code "false"} if such cookies should not included.
* An empty string ({@code ""}) means <em>undefined</em>.
* {@code "true"} means that the pre-flight response will include the header
* {@code Access-Control-Allow-Credentials=true}.
* <p>If undefined, credentials are allowed.
*/
String allowCredentials() default "";
springframework5.0.2
/** * Whether the browser should send credentials, such as cookies along with * cross domain requests, to the annotated endpoint. The configured value is * set on the {@code Access-Control-Allow-Credentials} response header of * preflight requests. * <p><strong>NOTE:</strong> Be aware that this option establishes a high * level of trust with the configured domains and also increases the surface * attack of the web application by exposing sensitive user-specific * information such as cookies and CSRF tokens. * <p>By default this is not set in which case the * {@code Access-Control-Allow-Credentials} header is also not set and * credentials are therefore not allowed. */ String allowCredentials() default "";
重点在这里
By default this is not set in which case the {@code Access-Control-Allow-Credentials} header is also not set and credentials are therefore not allowed.
原因是5.0.2后,allowCredentials默认为false了,再看 DefaultCorsProcessor
if (Boolean.TRUE.equals(config.getAllowCredentials())) {
responseHeaders.setAccessControlAllowCredentials(true);
}
allowCredentials为true时,返回的响应头AccessControlAllowCredentials属性才设置为true,允许客户端携带验证消息。
解决办法:
在注解中设置allowCredentials为true即可。
响应如下:
原文
https://segmentfault.com/a/1190000022999134
本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » Springboot 1.0 升级到 Springboot 2.0 @CrossOrigin 跨域问题