15

I`m trying to access a URL with Basic Authentication.

The URL returns JSON data.

How can I add my username and password to this http request below?

private postsURL = "https://jsonExample/posts";

getPosts(): Observable<AObjects []>{
    return this.http.get<AObjects[]>(this.postsURL); 
}
Daniel W.
  • 26,503
  • 9
  • 78
  • 128
YupYup
  • 153
  • 1
  • 1
  • 5
  • Can you use `post` method instead of `get` ? If you are using `get` then you should append credentials to the header of a request – komron Dec 04 '18 at 13:19
  • Have a look over here: https://stackoverflow.com/a/34465070/4736140 – komron Dec 04 '18 at 13:22

2 Answers2

23

Refer to https://angular.io/guide/http or https://v6.angular.io/guide/http#adding-headers

import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Basic ' + btoa('username:password')
  })
};

Then use the headers:

return this.http.get<AObjects[]>(this.postsURL, httpOptions); 
Daniel W.
  • 26,503
  • 9
  • 78
  • 128
  • 2
    thanks a lot . I try this and i get this as response Access to XMLHttpRequest at 'wwww.xxxxxx.de/re' from origin 'http://localhost:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. – YupYup Dec 04 '18 at 14:03
  • 1
    @YupYup Please ask a new question for a new problem. Basic Auth and CORS are two very different things. – Daniel W. Dec 04 '18 at 14:10
  • I added httpOptions as your advice. But now I have a new problem. The problem is get request transformed to Options request and server does not support Options Method. How can I send request as Get not Options? – kira Nov 09 '19 at 13:06
  • 1
    @kira are you using `http.get()` ? Do you use any header that relates to a different method, like pre-flight request? – Daniel W. Nov 09 '19 at 14:48
  • Yes I am using http.get().I wrote a question [Question](https://stackoverflow.com/questions/58779934/angular-8-httpclient-get-method-transforms-to-options-method) – kira Nov 09 '19 at 14:52
9

i don't know what you want to do exactly after getting authorized, but to get authorized using a simple call with basic authentication you need to do like this:

let authorizationData = 'Basic ' + btoa(username + ':' + password);

const headerOptions = {
    headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': authorizationData
    })
};

this.http
    .get('{{url}}', { headers: headerOptions })
    .subscribe(
        data => { // json data
            console.log('Success: ', data);
        },
        error => {
            console.log('Error: ', error);
        });
Kirk Larkin
  • 60,745
  • 11
  • 150
  • 162