Authorization bearer token Angular 5

2019-03-27 02:54发布

问题:

I am confused about how to create a good header for a simple Get request in Angular 5.

This is what I need to do in Angular:

This is what I have so far:

  getUserList(): Observable<UserList[]> {
    const headers = new Headers();
    let tokenParse = JSON.parse(this.token)             
    headers.append('Authorization', `Bearer ${tokenParse}`);
    const opts = new RequestOptions({ headers: headers });  
    console.log(JSON.stringify(opts));
    const users = this.http.get<UserList[]>(this.mainUrl, opts)
    return users
            .catch(this.handleError.handleError);         
  }

This is the response in my console.log:

{"method":null,"headers":{"Authorization":["Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImYwODZlM2FiYTk0ZjVhMjVmNDhiNzlkYmI2YWUwOWY4YzE2MTUyMzg2N2I5MDZiY2MzNWQyNWJiYTZmYTE4YjEwZjA1MjZiNThkZjE2Y2FjIn0.eyJhdWQiOiJmMDExY2M1OC00MGNlLTQzYTktOGY3MS04NDI0OTRlM2E5OTciLCJqdGkiOiJmMDg2ZTNhYmE5NGY1YTI1ZjQ4Yjc5ZGJiNmFlMDlmOGMxNjE1MjM4NjdiOTA2YmNjMzVkMjViYmE2ZmExOGIxMGYwNTI2YjU4ZGYxNmNhYyIsImlhdCI6MTUyMzU1MTQ0NSwibmJmIjoxNTIzNTUxNDQ1LCJleHAiOjE1MjM1NTQ0NDUsInN1YiI6IjIiLCJzY29wZXMiOlsiYXV0aGVudGljYXRlZCIsImFuZ3VkcnUiXX0.E-WdQTl7nPDW0gj0rohfql-QgnAinzvDxPR-pySMrG07XFY9tA6Ex7IL23pDBmKDmQO8RcZKa0L5r6SRQq9_iqzMWzn5Zxp94J9TJrpZ2KGMoLR_FbK_tpC5G5q5vUnCe3q34sH7cPdT_2cI704OWWaYmIUKKpXWUIG0PJw_uKSJ_uOifPv59RZGQkoaQ9gPywDKe-uamm1Faug-Kk2YnFMoEJq7ou19zyxgdpX80ZTPUae67uB0PGLRuvxfGaqVsJ8k0NunAY3-pyUnBwR_3eeuOxf4TyfW2aiOJ9kuPgsfV4Z1JD7nMpNtTHMJaXEyNkBW8RlYHD1pj4dkdnsDmw"]},"body":null,"url":null,"withCredentials":null,"responseType":null}

It looks pretty. But gives me this error

GET http://druang.dd:8080/user-list?_format=json 403 (Forbidden)

There is another clue to solve this mystery. In Sublime text, If I put the mouse over opts it says something like:

ERROR in src/app/services/userlist.service.ts(33,59): error TS2345: Argument of type 'RequestOptions' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'. Types of property 'headers' are incompatible. Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'. Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'. Index signature is missing in type 'Headers'.

Any idea?? Here is the full Git repo THanks for your help!

回答1:

I would suggest you to use an HTTPInteceptor which would take care of adding the token. Here is a great article to achieve that: https://www.illucit.com/angular/en-angular-5-httpinterceptor-add-bearer-token-to-httpclient-requests/

----- Another Way of solving the issue. -----

import { Http, Headers, Response } from '@angular/http';

getLoggedInUser(auth_token): Observable<any> { const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': auth_token }) return this.http.get(apiUrl, { headers: headers }) }

And do not forget to call and subscribe in your Component.



回答2:

Two things:

  1. headers.append(...) does not mutate the headers object, so your authorization header is not being sent. You need to do headers = headers.append(...)

  2. Try this.http.get<UserList[]>(this.mainUrl, { headers: headers });



回答3:

I used the following code and it works

import { HttpClient, HttpHeaders } from '@angular/common/http';

getServerList(){
    var reqHeader = new HttpHeaders({ 
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('mpManagerToken'))
     });
    return this.http.get<Server[]>(`${environment.apiUrl}/api/Servers/GetServerList`, { headers: reqHeader });
}


回答4:

I am not very good at programming,but with a little of try and failure if found this:

  getUserList(): Observable<UserList[]> {
    let tokenParse = JSON.parse(this.token)    
    // let myHeaders = new Headers();
    // myHeaders.set('Authorization', `Bearer ${tokenParse}`);
    // let options = new RequestOptions({ headers: myHeaders});
    const users = this.http.get<UserList[]>(this.mainUrl, { headers:new HttpHeaders().append('Authorization', `Bearer ${tokenParse}`)})
    // const users = this.http.get<UserList[]>(this.mainUrl, options);
    return users
            .catch(this.handleError.handleError);         
  }

It doesn't really matter if I use .set or .append, at the end of the day, it works in both cases...

I don't really know what is happening, so, if someone wants to explain it in the comments, you are welcome...