使用angular2发送身份验证凭据

时间:2017-02-28 09:36:11

标签: angular typescript angular2-http

我对angular2非常陌生,我试图通过http标头传递的auth凭据向本地API发出REST请求;我得到了以下代码:

        let headers = new Headers();
        headers.append('Accept', 'application/json')
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', 'Basic ' + btoa(user + ":" + password));
        let options = new RequestOptions({ headers: headers, withCredentials: true });

        return this.http.get("http://localhost:8080/api/test-credentials", options);

但我得到401:未经授权。 如果我尝试使用POSTMAN一切正常,生成的base64编码令牌是相同的,这是请求的对象:

[
    "http://localhost:8080/api/test-credentials",
    {
        "method":null,
        "headers":{
            "Accept":[
                "application/json"],
            "Content-Type":["application/json"],
            "Authorization":["Basic dXNlcjpwYXNzd29yZA=="]
        },
        "body":null,
        "url":null,
        "search":null,
        "withCredentials":true,
        "responseType":null
    }
]

1 个答案:

答案 0 :(得分:2)

使用以下身份验证发出请求:

  public getRequestWithBasicAuth(url: string, data): any {

        let headers = new Headers();
        headers.append("Content-Type", "application/json");
        headers.append("Authorization", "Basic " + data);

        let requestoptions = new RequestOptions({
            method: RequestMethod.Get,
            url: url,
            headers: headers
        });

        return this.http.request(new Request(requestoptions))
            .map((res: Response) => {
                let jsonObj: any;
                if (res.status === 204) {
                    jsonObj = null;
                }
                else if (res.status === 500) {
                    jsonObj = null;
                }
                else if (res.status === 200) {
                    jsonObj = res.json()
                }
                return [{ status: res.status, json: jsonObj }]
            })
            .catch(error => {
                return Observable.throw(error);
            });
    }

然后在提交登录调用上面的函数:

  onLogin(formData) {
    let url = this.global_service.base_path + 'something...';
    let data = btoa(formData.email.toLowerCase() + ':' +  formData.password);

    this.global_service.getRequestWithBasicAuth(url, data)
      .subscribe(res => {
        if (res[0].status == 200) {
        // Do what you want after login..
        }
      }
}