Angular 6 HTTP Get request with HTTP-Basic authentication

40,310

Solution 1

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

Solution 2

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);
        });
Share:
40,310
YupYup
Author by

YupYup

Updated on July 10, 2022

Comments

  • YupYup
    YupYup almost 2 years

    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); 
    }
    
  • YupYup
    YupYup over 5 years
    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.
  • Daniel W.
    Daniel W. over 5 years
    @YupYup Please ask a new question for a new problem. Basic Auth and CORS are two very different things.
  • ronypatil
    ronypatil about 5 years
    for {headers: headerOptions} . I am getting issue : cant be assigned as RequestOptions
  • kira
    kira over 4 years
    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?
  • Daniel W.
    Daniel W. over 4 years
    @kira are you using http.get() ? Do you use any header that relates to a different method, like pre-flight request?
  • kira
    kira over 4 years
    Yes I am using http.get().I wrote a question Question
  • daniel-sc
    daniel-sc over 2 years
    be aware that this fails for non-ascii characters: developer.mozilla.org/en-US/docs/Glossary/…
  • zdnmn
    zdnmn about 2 years
    Hello, btoa(username:password) there is a problem with some characters, like üçşğöÖŞĞ? How can I solve this.