Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
}
like image 442
YupYup Avatar asked Dec 04 '18 12:12

YupYup


2 Answers

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); 
like image 68
Daniel W. Avatar answered Oct 20 '22 14:10

Daniel W.


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);
        });
like image 15
Mohammad Khodabandeh Avatar answered Oct 20 '22 15:10

Mohammad Khodabandeh