在后端Angular 2 + Spring Boot中没有接收到授权头

时间:2017-08-20 16:57:51

标签: java angular spring-boot cors jwt

我正在尝试在http请求中传递授权标头:

我的角色代码是这样的:

 let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', this.uriRequest.appendAuthHeaderValue());
        let options = new RequestOptions({ headers: headers });

        console.log(JSON.stringify(options));

        this.http.post(this.urlManager.BASE_URL + this.urlManager.customerServiceURL, body, options).map(
            (response) => {
                console.log(JSON.stringify(response));
            });

在控制台上我可以发现在选项中我的授权标题已正确设置:

{"method":null,"headers":{"Content-Type":["application/json"],"Authorization":["eyJhbGciOiJIUzIiJ9.eyJleHAiOjE1MDMyNTQ4NDIsInN1YiI6Ild25ldyIsInVzZXJJZCI6ImRlbW8iLCJyb2xlIjoiVFUiJ9.OvS69uweYIB96mQLt61RQVyoPnbY0aUhqpzUvHu40"]},"body":null,"url":null,"withCredentials":null,"responseType":null}

但在我的后端,我无法获得令牌:

我的COROS Filer:

HttpServletResponse res = (HttpServletResponse) response;
    HttpServletRequest  req = (HttpServletRequest) request;

res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", " x-requested-with, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, Connection, User-Agent, Authorization, sw-useragent, sw-version");
res.setHeader("Access-Control-Expose-Headers", "Authorization");

    // Just REPLY OK if request method is OPTIONS for CORS (pre-flight)
    if ( req.getMethod().equals("OPTIONS") ) {
    res.setStatus(HttpServletResponse.SC_OK);
    return;
}
    chain.doFilter(request, response);

我得到了这样的令牌:

final String token = request.getHeader("Authorization");

请帮助我,我无法从这里继续。

附加屏幕:

OPTION: enter image description here

POST:

enter image description here

响应标题: enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

如果你仍然没有找到答案。在这里。

角度中的标题是不可变的。所以headers.append()实际上返回一个新的标题,旧标题保持不变。

你必须使用它,

let headers = new Headers();
headers = headers.append("some-header", "value");
headers = headers.append("another-header", "another-value");

然后传递这个标题。