从Angular 2 http get请求的PHP Backend中忽略授权标头

时间:2016-11-12 19:45:29

标签: php angular ionic2

我正在尝试使用以下代码从我的离子2应用程序发送授权标头:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class MembersService {

    private baseUrl = 'http://xxx';
    constructor(private http: Http) { 

    }

    getMemberlist() {
        return new Promise(resolve => {
            this.http.get(`${this.baseUrl}`, this.jwt())
                .map(res => res.json())
                .subscribe(res => resolve(res.v_members));
        });
    }

    private jwt() {
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (currentUser && currentUser.token) {
            let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token });
            console.log(headers);

            return new RequestOptions({ headers: headers });
        }
    }
}

在PHP后端我用以下内容查看标题:

$headers = getallheaders();
file_put_contents("headers.txt", print_r($headers, true));

并获得以下输出:

Array
(
    [Host] => xxx
    [Connection] => close
    [Access-Control-Request-Method] => GET
    [Origin] => http://localhost:8100
    [User-Agent] => Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko$
    [Access-Control-Request-Headers] => authorization
    [Accept] => */*
    [Referer] => http://localhost:8100/
    [Accept-Encoding] => gzip, deflate, sdch
    [Accept-Language] => de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
)

我已经在.htaccess中添加了以下内容:

RewriteCond %{HTTP:Authorization} ^(.+)
RewriteRule ^(.*)$ $1 [E=HTTP_AUTHORIZATION:%1,PT]

当我使用邮递员连接API时,会出现授权标题:

Array
(
    [Authorization] => Bearer test_token
    [Host] => xxx
    [Connection] => close
    [Cache-Control] => no-cache
    [User-Agent] => Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.$
    [Postman-Token] => 9b51b6fe-2c24-564c-9998-1acb5b02136e
    [Accept] => */*
    [Accept-Encoding] => gzip, deflate, sdch
    [Accept-Language] => de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
    [Cookie] => PHPSESSID=uiboq2m0isfgb16kfrr9dtbji1
)

我在这里缺少什么?

编辑:

设置localstorage的代码:

登录的响应没有问题。用户和令牌在localstorage中设置

   login(username, password) {
        return this.http.post(this.baseUrl, JSON.stringify({ username: username, password: password }))
            .map((response: Response) => {
                let user = response.json();
                if (user && user.token) {
                    localStorage.setItem('currentUser', JSON.stringify(user));
                }
            });
    }

1 个答案:

答案 0 :(得分:0)

我终于找到了解决方案。 问题是,我误解了错误响应。来自angular的HTTP-Request正在发送一个预检,该预检被我的后端的401响应拒绝。实际的请求从未发送过。我在上面发布的标题是预检的标题,因此没有任何授权。在我改变后端以正确响应预检后,发送请求包括授权标题。