0

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?

Kiril1512
  • 2,522
  • 2
  • 10
  • 30

1 Answers1

1

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.

kris_IV
  • 1,908
  • 17
  • 37
  • 1
    I think that I have another idea why you have a problem with this request. Look, that `401` you get for `Option` request, not for `GET` and this is a difference between your `browser` version and `REST client` request, where you don't have `CORS` issue. I think that your problem is not a Angular App but Java server. In normal way you should get `200` from `OPTION` and eventually `401` from `GET`. I think that you should disable `OPTION` request from your Authentication process. – kris_IV Jan 25 '19 at 12:45
  • you mean disable OPTION in the back-end? – Kiril1512 Jan 25 '19 at 14:42
  • Not disable `OPTION`, but disable authentication for `OPTION` request. I had similar problem few years ago with `PHP Symfony` framework, and I found solution where `OPTION` request get round authentication process. This is very important because OPTION request doesn't have custom headers, so authentication can't pass for them. – kris_IV Jan 25 '19 at 14:44
  • Did you found solution? – kris_IV Jan 25 '19 at 14:50