YupYup
YupYup

Reputation: 303

Angular 6 HTTP Get request with HTTP-Basic authentication

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); 
}

Upvotes: 30

Views: 67395

Answers (3)

Florian
Florian

Reputation: 1

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); 

Upvotes: 0

Mohammad Khodabandeh
Mohammad Khodabandeh

Reputation: 965

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);
        });

Upvotes: 17

Daniel W.
Daniel W.

Reputation: 32350

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); 

Upvotes: 47

Related Questions