Search code examples
angularauthenticationhttp-headers

Angular - authentication headers


I have an Java backend that provides me some API's that are protected with authentication.

So if I call it using any browser or postman with Authorization I have an 200 (Ok) response, but If I set httpHeaders with the same user and password, I get 401 (Unauthorized).

The call:

let username: string = 'admin';
let password: string = 'pe';
let headers =  new HttpHeaders().set('Authorization' , 'Basic ' + btoa(username + ':' + password)).set('Content-Type', 'application/json').set('cache-control', 'no-cache'); 
console.log(headers);

let params = new HttpParams().set('instID', value).set('procType', 'M');
    
return this.httpClient.get<pe_process_instance[]>('http://' + this.urlConfig.BASE_URL + ':' + this.urlConfig.PORT + '/' + this.urlConfig.WSBaseURL + '/getipeprocessinstances', { headers: headers , params: params });

The response:

response image

What I am missing here? Do I correctly set my headers?


Solution

  • Try to set your headers in this way:

    let headers = new HttpHeaders();
    
    headers = headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));
    headers = headers.append('Content-Type', 'application/json');
    headers = headers.append('cache-control', 'no-cache');
    

    When you use .set() multiple times you overwrite your headers each time, and only last header is send.