首页 文章

Angular 2:获取授权 Headers

提问于
浏览
6

在我的应用程序(Angular 2 / Ionic 2)中,我实现了自己的登录/身份验证 . 基本上它的工作方式如下:在登录时,PHP后端正在验证用户名和密码 . 生成令牌,然后将其发送回 Headers 中的前端(授权) . 后端的响应如下:

HTTP/1.1 200 OK
Host: localhost:8080
Connection: close
X-Powered-By: PHP/5.6.28
Set-Cookie: PHPSESSID=jagagi2le1b8i7r90esr4vmeo6; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Type: application/json
 Authorization: d7b24a1643a61706975213306446aa4e4157d167eaad9aac989067a329c492d3
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Origin, Authorization
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Content-Length: 301

显然有一个带有令牌的Authorization标头 . CORS似乎也可以正确设置,因为我在Allow-Headers标头中看到了Authorization .

但是,当我尝试在Angular 2中获取头时,它总是返回null:

private extractDataAndSetAuthHeader(res: Response) {

    // Set auth header if available.
    // If not available - user is not logged in. Then 
    // we also have to remove the token from localStorage
    if(res.headers.has("Authorization"))
    {
        let token = res.headers.get("Authorization");

        this.setToken(token);
    }
    else
    {
        // If no token is sent, remove it
        this.removeToken();
    }

    let body = res.json();
    return body.data || { };
}

该方法的第一行返回false . 另外,当我在我的回复中检查 Headers 对象时,它只显示以下内容(Chrome开发工具):

[[Entries]]:
Array[4]
0:{"pragma" => Array[1]}
1:{"content-type" => Array[1]}
2:{"cache-control" => Array[1]}
3:{"expires" => Array[1]}

该对象中没有Authorization标头 .

有人可以帮帮我吗?

提前致谢 :)

3 回答

  • 17

    这个答案对我有帮助:link

    它显示了如何在后端添加它以及如何在前端使用它

    Java后端:

    public void methodJava(HttpServletResponse response){
    ...
    response.addHeader("access-control-expose-headers", "Authorization");
    }
    

    并像这样访问角度的 Headers :

    return this.http
        .get(<your url here for your backend>)
        .map(res => console.log("cookie: " + res.headers.get("Authorization") )
    }
    
  • 3

    只是想发布答案,因为它可能会帮助其他人:解决方案设置

    Access-Control-Expose-Headers: Authorization
    

    然后 - 前端也可以读取Authorization标头 .

  • 0

    这与Angular无关 . 问题是默认情况下CORS限制标头,并且在调用CORS请求时您看不到“授权”标头 . 所以,调整服务器让它发送授权头

    必须提供Access-Control-Allow-Headers以响应OPTIONS请求(飞行前) .

    Access-Control-Expose-Headers must be provided in response of POST/GET request.

    Access-Control-Expose-Headers:授权

相关问题