27

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.
  • 31,164
  • 13
  • 93
  • 151
YupYup
  • 273
  • 1
  • 3
  • 6
  • 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

3 Answers3

45

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.
  • 31,164
  • 13
  • 93
  • 151
  • 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
  • 3
    @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? – Geshe 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) – Geshe Nov 09 '19 at 14:52
  • Hello, btoa(username:password) there is a problem with some characters, like üçşğöÖŞĞ? How can I solve this. – zdnmn Mar 03 '22 at 07:13
17

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
  • 84,915
  • 16
  • 214
  • 203
  • 1
    for {headers: headerOptions} . I am getting issue : cant be assigned as RequestOptions – ronypatil Feb 15 '19 at 07:01
  • be aware that this fails for non-ascii characters: https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem – daniel-sc Nov 25 '21 at 10:30
0

Since btoa() ist deprecated the following might be a cleaner solution than https://stackoverflow.com/a/53613780

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

const username = 'JohnDoe'
const password = 'JonhnsSecret'

const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64');

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

Then use the headers:

return this.http.get<AObjects[]>(this.postsURL, httpOptions); 
Kvothe
  • 1
  • 1