Help with authentication REST API via token


Good night Everybody.

I present myself in the forum as new in the IONIC world. I’ve only had a couple of weeks of learning and practice, specifically in Ionic 2 … so far so good, however I have encountered difficulties in the use of external APIs, especially those that are accessed through Token authentication. I tried to adapt the following code from an online tutorial without success:

import {Injectable} from ‘@ angular / core’;
import {Http} from ‘@ angular / http’;
import ‘rxjs / add / operator / map’;
import ‘rxjs / add / operator / toPromise’;

@Injectable ()
export class UserService {

private http: Http
) {}

getUsers () {
return this.http.get (‘’)
.map (res => res.json ())
.toPromise ();

What I’m looking for is to access an API to which a GET request is made by means of a header authorization in base64 that should be like this:

Authorization: Basic bmV5c2EuaHVydGFkb0BnbWFpbC5jb206MTY3YmM2OTE1MmY5ZWQxMWFjNzc =

I’ve been looking for a solution for days and I do not get it. Any help they can give me would be very valuable.

It should be noted that I am still a rookie.

Thanks in advance.

best regards.


this is most likely a CORS issue (cross origin script).


import { Component } from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';

  selector: 'page-wscall',
  templateUrl: 'wscall.html',
export class WscallPage {
  webReturn: any;

  constructor(private http: Http) {

  callWebserviceTest3() {

    in ionic.config.json is a proxy setup
    "proxies": [{
        "path": "/ru",
      "proxyUrl": ""

    const baseURL = '/ru/api/?'
    const baseParams = 'results=25';

    let testURL = (baseURL+baseParams);
    let authHeader = 'Basic bmV5c2EuaHVydGFkb0BnbWFpbC5jb206MTY3YmM2OTE1MmY5ZWQxMWFjNzc =';

    let headersObj = new Headers();
    headersObj.append('Authorization', authHeader);


    this.http.get(testURL, {headers:headersObj})
      .map((res:Response) => res.json())
      .subscribe(res => {
        this.webReturn = res;







<ion-content padding>
  <p>WS Calling Page</p>

        <button ion-button (click)="callWebserviceTest3()">forum test</button>
        <p>Result: <br>
          <ion-scroll scrollY="true" scrollX="true">
            <pre>{{ webReturn | json}}</pre>





I try that but i get an error…please provide solution.


I would need to see the code to provide a solution


ok i give the code of .ts file


i dont need screen shot, I need copy paste of the whole ts


import {Component, ViewChild} from ‘@angular/core’;
import {IonicPage, Navbar, NavController, NavParams} from ‘ionic-angular’;
import {Http,Headers} from “@angular/http”;
import “rxjs/add/operator/map”;

selector: ‘page-add-new-member’,
templateUrl: ‘add-new-member.html’,

export class AddNewMemberPage {
@ViewChild (Navbar) navbar:Navbar;
constructor(public navCtrl: NavController, public navParams: NavParams, public http:Http) {

ionViewDidLoad() {
console.log(‘ionViewDidLoad AddNewMemberPage’);

this.navbar.backButtonClick = (e:UIEvent)=>{
  // todo something

let headers: Headers = new Headers();

headers.append("Authorization", "Basic " + btoa('username' + ":" + 'password'));

this.http.get('http://localhost/abcd/view/view_relation.php',  {headers: headers})
  .map(res => res.json())
  .subscribe(data => {

  },(error) => {




You can’t localhost from lab, Http is for external addresses

You may be able to access thru Proxy setup


Here is my wokring route code for get requests, maybe this helps:

import { Http, Headers, RequestOptions} from '@angular/http';
  getObjects(): Promise<any> {
    return new Promise((resolve, reject) => {
      this.http.get(SERVER_ADDRESS + ROUTE_OBJECTLIST, this.getHttpHeader())
        data => {
        }, err => {
          console.log("Error in server-communication.ts: Getting objects failed: ");
  getHttpHeader(): RequestOptions{
    return new RequestOptions({ headers: new Headers(
        'Authorization' : TOKEN_PREFIX + this.storageProv.userToken,
        'content-Type'  : 'application/json',
        'Accept'        : 'application/json'


Thank You Hesters and Ben1nB1ack for thehelp.


i want to make validation of login page like if username or password is wrong then display error message like ‘please enter valid credential’. so can u help me please?


Just google please before you ask such questions.

But here you go, watch this:


Thats way to complicated what you can read here :smiley:
How about a simple Angular interceptor?


Okay, Thank you mr. Hesters and LoL Stats


anyone help me pls, i have the same problem…

import { Http, Headers } from '@angular/http';

private dispositivo = {
    "device_id" : "cleiton_device",
    "device_os_version" : "5.0",
    "device_model" : "ASUS_T00J",
    "device_name" : "ZENFONE",
    "device_manufacturer" : "ASUS INC",
    "device_api_version" : "19",
    "device_width": "800",
    "device_height": "600",

    public http: Http
  ) {

  efetuarLogin(matricula:string, senha:string) {
    return new Promise((resolve, reject) => {
        let headers = new Headers();
        //headers.append("Authorization", "Basic" + btoa(matricula + ":" + senha));
        headers.append("Authorization", "Basic MjAyODkzMTUxOjAxMDEyMDAx");
        headers.append('Content-Type', 'application/json');
        console.log(headers); + '/login/loginapp', this.dispositivo, {headers: headers})
          .subscribe(res => {
          }, (err) => {

error :
Failed to load API_KEY: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8100’ is therefore not allowed access. The response had HTTP status code 405.