0

I had the following code to do a get http call without authentication and everything worked fine.

let headers2 = {'Content-Type': 'application/json'}; his.http.get('https://api.test.com/account/get/',headers2).map(res => res.json()).subscribe(data => { this.posts = data;});

But I don't know how to add in the above basic authentication, like this (in curl) but in ionic:

curl --user admin:password -s -X GET "https://api.test.com/account/get/" -H "content-type: application/json"

Whatever I tried a take a 401 authentication error.

Thank you

cmall
  • 11
  • 1
  • 2

2 Answers2

1

You can add basic authorization by appending it in headers, as below:

var headers_object = new HttpHeaders();
headers_object.append('Content-Type', 'application/json');
headers_object.append("Authorization", "Basic " + btoa("admin:password"));

const httpOptions = {
  headers: headers_object
};
Prachi
  • 3,478
  • 17
  • 34
0

I am getting 401 error...I used:

let headers = new Headers(); headers.append('Authorization', 'Basic '+ btoa('admin:password'));

headers.append('Access-Control-Allow-Headers', 'Content-Type');

headers.append('Access-Control-Allow-Origin', '*');

headers.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS')

let options = new RequestOptions({headers: headers}); this.http.get('https://api.test.com/account/get/',options).map(res => res.json()).subscribe(data => { ....

And the result...

Request URL: https://api.test.com/account/get Request Method: OPTIONS Status Code: 401 Unauthorized Remote Address: 75.127.10.64:443 Referrer Policy: no-referrer-when-downgrade Connection: keep-alive Content-Length: 590 Content-Type: text/html Date: Sat, 16 Jun 2018 19:02:06 GMT Keep-Alive: timeout=10 Server: nginx WWW-Authenticate: Basic realm="Protected" Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 Access-Control-Request-Headers: access-control-allow-headers,access-control-allow-methods,access-control-allow-origin,authorization Access-Control-Request-Method: GET Connection: keep-alive Host: api.test.com Origin: http://localhost:8100 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36

cmall
  • 11
  • 1
  • 2