Angular 2: get authorization header

in my application (Angular 2 / Ionic 2) I implemented my own login / authentication. This basically works as follows: when you log in, the username and password are checked using a PHP server. A token is created, which is sent back to the header in the header (authorization). The response from the backend is as follows:

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

Obviously, there is an authorization header with a token present. CORS is also configured correctly, as I see authorization in the Allow-Headers header.

But when I try to get the header in Angular 2, it always returns 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 || { };
}

The first line of the method returns false. Also, when I check the header object in my answer, it shows me only the following (Chrome dev tools):

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

There is no authority header in this object.

- ?

:)

+6
3

, :

Access-Control-Expose-Headers: Authorization

- frontend .

+17

:

,

Java:

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

angular :

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

This is not related to Angular. The problem is that CORS restricts the default headers, and you do not see the "Authorization" header when invoking CORS requests. So, configure the server to send an authorization header

Access-Control-Allow-Headers should be provided in response to an OPTIONS request (pre-flight).

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

Access-Control-Expose-Headers: Authorization

0
source

Source: https://habr.com/ru/post/1015081/


All Articles