http post - how to send Authorization header?

190,650

Solution 1

Ok. I found problem.

It was not on the Angular side. To be honest, there were no problem at all.

Reason why I was unable to perform my request succesfuly was that my server app was not properly handling OPTIONS request.

Why OPTIONS, not POST? My server app is on different host, then frontend. Because of CORS my browser was converting POST to OPTION: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/

With help of this answer: Standalone Spring OAuth2 JWT Authorization Server + CORS

I implemented proper filter on my server-side app.

Thanks to @Supamiu - the person which fingered me that I am not sending POST at all.

Solution 2

you need RequestOptions

 let headers = new Headers({'Content-Type': 'application/json'});  
 headers.append('Authorization','Bearer ')
 let options = new RequestOptions({headers: headers});
 return this.http.post(APIname,body,options)
  .map(this.extractData)
  .catch(this.handleError);

for more check this link

Solution 3

I believe you need to map the result before you subscribe to it. You configure it like this:

  updateProfileInformation(user: User) {
    var headers = new Headers();
    headers.append('Content-Type', this.constants.jsonContentType);

    var t = localStorage.getItem("accessToken");
    headers.append("Authorization", "Bearer " + t;
    var body = JSON.stringify(user);

    return this.http.post(this.constants.userUrl + "UpdateUser", body, { headers: headers })
      .map((response: Response) => {
        var result = response.json();
        return result;
      })
      .catch(this.handleError)
      .subscribe(
      status => this.statusMessage = status,
      error => this.errorMessage = error,
      () => this.completeUpdateUser()
      );
  }

Solution 4

If you are like me, and starring at your angular/ionic typescript, which looks like..

  getPdf(endpoint: string): Observable<Blob> {
    let url = this.url + '/' + endpoint;
    let token = this.msal.accessToken;
    console.log(token);
    return this.http.post<Blob>(url, {
      headers: new HttpHeaders(
        {
          'Access-Control-Allow-Origin': 'https://localhost:5100',
          'Access-Control-Allow-Methods': 'POST',
          'Content-Type': 'application/pdf',
          'Authorization': 'Bearer ' + token,
          'Accept': '*/*',
        }),
        //responseType: ResponseContentType.Blob,
      });
  }

And while you are setting options but can't seem to figure why they aren't anywhere..

Well.. if you were like me and started this post from a copy/paste of a get, then...

Change to:

  getPdf(endpoint: string): Observable<Blob> {
    let url = this.url + '/' + endpoint;
    let token = this.msal.accessToken;
    console.log(token);
    return this.http.post<Blob>(url, null, { //  <-----  notice the null  *****
      headers: new HttpHeaders(
        {
          'Authorization': 'Bearer ' + token,
          'Accept': '*/*',
        }),
        //responseType: ResponseContentType.Blob,
      });
  }

Solution 5

I had the same issue. This is my solution using angular documentation and firebase Token:

getService()  {

const accessToken=this.afAuth.auth.currentUser.getToken().then(res=>{
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': res
    })
  };
  return this.http.get('Url',httpOptions)
    .subscribe(res => console.log(res));
}); }}
Share:
190,650
Maciej Treder
Author by

Maciej Treder

Updated on July 09, 2022

Comments

  • Maciej Treder
    Maciej Treder almost 2 years

    How do you add headers to your http request in Angular2 RC6? I got following code:

    login(login: String, password: String): Observable<boolean> {
        console.log(login);
        console.log(password);
        this.cookieService.removeAll();
        let headers = new Headers();
        headers.append("Authorization","Basic YW5ndWxhci13YXJlaG91c2Utc2VydmljZXM6MTIzNDU2");
        this.http.post(AUTHENTICATION_ENDPOINT + "?grant_type=password&scope=trust&username=" + login + "&password=" + password, null, {headers: headers}).subscribe(response => {
          console.log(response);
        });
        //some return
    }
    

    The problem is, that angular doesn't add Authorization header. Instead of that, in request I can see following additional headers:

    Access-Control-Request-Headers:authorization
    Access-Control-Request-Method:POST
    

    and sdch added in Accept-Encoding:

    Accept-Encoding:gzip, deflate, sdch
    

    Unfornately there is no Authorization header. How should I add it correctly?

    Whole request sent by my code looks as follow:

    OPTIONS /oauth/token?grant_type=password&scope=trust&username=asdf&password=asdf HTTP/1.1
    Host: localhost:8080
    Connection: keep-alive
    Pragma: no-cache
    Cache-Control: no-cache
    Access-Control-Request-Method: POST
    Origin: http://localhost:3002
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
    Access-Control-Request-Headers: authorization
    Accept: */*
    Referer: http://localhost:3002/login
    Accept-Encoding: gzip, deflate, sdch
    Accept-Language: en-US,en;q=0.8,pl;q=0.6
    
  • Maciej Treder
    Maciej Treder over 7 years
    The point of question is not how to deal with http response, but how to add proper header to request. For sure I checked your proposal - it doesn't work, sent headers are still same.
  • Maciej Treder
    Maciej Treder over 7 years
    What version of angular you got?
  • John Baird
    John Baird over 7 years
    I'm using angular RC6
  • Maciej Treder
    Maciej Treder over 7 years
    Did you make some additional configuration of http request?
  • Maciej Treder
    Maciej Treder over 7 years
    Huh...On my end it is not working... Don't know why... This is my http ver: "@angular/http": "^2.0.0-rc.6", are you sure you have same?
  • Maciej Treder
    Maciej Treder over 7 years
    Could you show me headers which are sent with your request?
  • John Baird
    John Baird over 7 years
    Its in my code sample... Content-Type and Authorization
  • Oskar
    Oskar almost 7 years
    It sends OPTIONS as a preflight request and then the POST if everything goes fine. It's not replacing POST with OPTIONS.
  • Joyal
    Joyal over 6 years
    headers.append("Authorization", "Bearer " + t; this line missing closing parenthesis.
  • rism
    rism almost 5 years
    Access-Control headers are set by the server, not the client as is Content-Type