# Spring API 的 CORS 测试 提示错误 Reason: header ‘authorization’ is not allowed

**URL:** <https://www.isharkfly.com/t/spring-api-cors-reason-header-authorization-is-not-allowed/639>\
**Category:** 程序语言\
**Tags:** spring, java\
**Created:** [November 4, 2020, 4:09pm UTC](https://www.isharkfly.com/t/spring-api-cors-reason-header-authorization-is-not-allowed/639 "2020-11-04T16:09:11Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [November 4, 2020, 4:09pm UTC](https://www.isharkfly.com/t/spring-api-cors-reason-header-authorization-is-not-allowed/639/1 "2020-11-04T16:09:12Z")

</div>

在使用 CORS 测试的时候，我们得到下面的错误提示：

```auto
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/search/user. (Reason: header ‘authorization’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response).

```

![cors-authorization-01](https://www.isharkfly.com/images/transparent.png)

## 问题解决

如果你使用的是 Spring 进行 API 编写的话。

出现这个问题的原因在于你返回的 http 请求的 header Authorization 这个选项。

在你的过滤器中，你应该添加下面的一段内容：

```auto
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");

```

需要注意的是，根据官方的文档中的说明 Access-Control-Allow-Headers: \* 是可以使用通配符的。

但是 Authorization 的头不能使用通配符，必须单独列出。

因此，需要在 Spring API 返回的头中添加上面的代码。

上面的代码表示告诉前端 CORS 的设置，以避免出现跨域访问的问题。

![cors-authorization-02](https://www.isharkfly.com/images/transparent.png)

上面的配置，你可以在 Spring 的过滤器中进行配置。

当你配置成功后重启服务器，在进行跨域测试。

你会看到测试成功的提示：

![cors-authorization-03](https://www.isharkfly.com/images/transparent.png)

同时在浏览器的网络调试部分，我们应该能够看到相应的头中也添加了 Authorization。

![cors-authorization-04](https://www.isharkfly.com/images/transparent.png)

跨域访问比较难调试的问题就是不同的地方有不同的错误，需要根据前端和后端同时来进行调试。但，浏览器的调试窗口也给了比较完整的提示。

按照浏览器的调试提示来调试就可以了。
