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?

4
  • 1
    i think best practice is use interceptor Commented Jan 25, 2019 at 11:13
  • follow this answer stackoverflow.com/questions/51989482/… Commented Jan 25, 2019 at 11:16
  • @Abhishek don't see how the answer will help me :/ Commented Jan 25, 2019 at 12:02
  • Well, this seems to fail on the options request, seems to me that this is a CORS issue. Have you correctly setup CORS in backend? Commented Jan 25, 2019 at 17:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
you mean disable OPTION in the back-end?
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.
Did you found solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.