32

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); 
}
2
  • Can you use post method instead of get ? If you are using get then you should append credentials to the header of a request Commented Dec 4, 2018 at 13:19
  • Have a look over here: stackoverflow.com/a/34465070/4736140 Commented Dec 4, 2018 at 13:22

3 Answers 3

49

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); 
Sign up to request clarification or add additional context in comments.

6 Comments

thanks a lot . I try this and i get this as response Access to XMLHttpRequest at 'wwww.xxxxxx.de/re' from origin '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 Please ask a new question for a new problem. Basic Auth and CORS are two very different things.
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 are you using http.get() ? Do you use any header that relates to a different method, like pre-flight request?
Yes I am using http.get().I wrote a question Question
|
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);
        });

2 Comments

for {headers: headerOptions} . I am getting issue : cant be assigned as RequestOptions
be aware that this fails for non-ascii characters: developer.mozilla.org/en-US/docs/Glossary/…
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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.