SpringBoot 2.0 @CrossOrigin 无法跨域问题

在SpringBoot2.0(springframework5.0.2后)中,使用@CrossOrigin注解配置跨域时,需注意allowCredentials默认为false,导致带cookie的跨域请求失败。本文详细解析问题原因,并提供解决方案,通过设置allowCredentials为true来成功实现跨域。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前使用SpringBoot 1.5.x,配置跨域一般是直接在controller或是在某一个方法上添加 @CrossOrigin 注解即可,如下代码

/**
 * @author chenws
 * @decription
 * @date 2018/10/18
 */
@RestController
@RequestMapping(value = "xxx")
@CrossOrigin(maxAge = 3600)
public class BuildShapeController {
 
        @CrossOrigin(maxAge = 3600)
	@ApiOperation("xxx")
	@RequestMapping(value = "/xxx",method = RequestMethod.POST)
	public ResponseVO<List<xxx>> listShape(@RequestBody xxx xxx){}
}

没有任何问题,使用的非常好,但是在spring boot 2.0中(springframework5.0.2后),以上方法行不通,这样设置无效。在网上找了n篇文章,都是按照SpringBoot 1.x的方法介绍的,始终无法解决,知道发现碩果兄的这篇文章,问题才得以解决,再次表示万分感谢。文章地址:SpringBoot 2.0 @CrossOrigin 无法跨域问题

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

allowCredentialstrue时,返回的响应头AccessControlAllowCredentials属性才设置为true

因此凡是客户端带上cookie的请求,都不能实现跨域。

 

解决办法:

在注解中设置allowCredentialstrue即可。

@CrossOrigin(allowCredentials="true",maxAge = 3600)

至此,问题完美解决

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值