【问题标题】:CORS Preflight request - Custom auth token in header - Spring and Angular 4CORS Preflight 请求 - 标头中的自定义身份验证令牌 - Spring 和 Angular 4
【发布时间】:2018-04-23 23:07:42
【问题描述】:

我在本地服务器上使用令牌作为标头请求简单 GET 时遇到问题。 我的浏览器不断通过简单的 GET 请求发送预检请求。

我用 postman / curl 试过了,没有任何问题。

这是实际代码: 服务器(春季):

@Override
public void doFilter(final ServletRequest req, final ServletResponse res,
                     final FilterChain chain) throws IOException, ServletException {
    final HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods",
            "POST, GET, PUT, OPTIONS, DELETE, PATCH");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with, x-auth-token, Content-Type");
    response.setHeader("Access-Control-Expose-Headers", "x-auth-token");
    response.setHeader("Access-Control-Allow-Credentials", "true");

    final HttpServletRequest request = (HttpServletRequest) req;

    if (request.getMethod().equals("OPTIONS")) {
        try {
            response.getWriter().print("OK");
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        chain.doFilter(request, response);
    }
}

所以我的x-auth-token 是一个类似 jwt 的令牌。

在我的 Angular 代码中,我只是将我的令牌添加为 x-auth-token,如下所示:

getAll() {
    return this.http.get('http://127.0.0.1:8080/module', this.jwt()).map((response: Response) => response.json());
}

private jwt() {
    // create authorization header with jwt token
    let token = localStorage.getItem('user');
    let obj = JSON.parse(token)
    console.log(obj.token.token)
    if (obj.token) {
        let headers = new Headers({
            'x-auth-token': obj.token.token,
            'Content-Type': "application/json"
        });
        return new RequestOptions({ headers: headers });
    }
}

请注意,我的身份验证/注册路由工作正常,我只是无法将我的 x-auth-token 标头传送到我的 Spring 服务器。

我的两个网络服务器都在本地运行:8080 上的 Spring 和 8000 上的 Angular。

任何帮助将不胜感激,

谢谢,

【问题讨论】:

  • 您的令牌应该是string 类型还是json 对象?
  • 这是string
  • 您可以在 teamviewer 中使用吗?还是谷歌浏览器远程桌面?
  • 感谢您的提问,但我在工作计算机上,无法访问屏幕共享。
  • 我可以调试并找出问题

标签: spring angular cors jwt


【解决方案1】:

首先,postman 和 curl 不是测试 CORS 的好方法,因为它们不强制执行与标准浏览器相同的源策略。即使在浏览器中失败的情况下,它们也能正常工作。

其次,您的请求被浏览器预先发送的原因是它不是simple request,因为x-auth-token 标头和application/json Content-Type。只有application/x-www-form-urlencoded 简单请求中允许使用 multipart/form-datatext/plain 内容类型。

我认为问题出在 OPTION 响应中。确保它包含所有相关的标题。它可能会失败,或者您正在丢失添加的标头,因为您处理它的方式与其他响应不同。

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多