Help with authentication REST API via token

#1

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 {

builder(
private http: Http
) {}

getUsers () {
return this.http.get (‘https://randomuser.me/api/?results=25’)
.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.

#2

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

wscall.ts

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


@Component({
  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": "https://randomuser.me"
            }]


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

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

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

    console.log(testURL);
    console.log(authHeader);

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


  }

}

wscall.html

<ion-header>

  <ion-navbar>
    <ion-title>wscall</ion-title>
  </ion-navbar>

</ion-header>


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

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

        </p>
      </ion-col>
    </ion-row>
  </ion-grid>



</ion-content>

image

#3

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

#4

I would need to see the code to provide a solution

#5

ok i give the code of .ts file

#6

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

#7

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

@IonicPage()
@Component({
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
  this.navCtrl.popToRoot();
};

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 => {

    console.log(data);
  },(error) => {
    console.log(error);
  });

}

}

#8

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

You may be able to access thru Proxy setup

#9

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())
      .subscribe(
        data => {
          resolve(data.json());
        }, err => {
          console.log("Error in server-communication.ts: Getting objects failed: ");
          console.log(err);
          reject(err);
        }
      );
    });
  }
  getHttpHeader(): RequestOptions{
    return new RequestOptions({ headers: new Headers(
      {
        'Authorization' : TOKEN_PREFIX + this.storageProv.userToken,
        'content-Type'  : 'application/json',
        'Accept'        : 'application/json'
      }
    )});
  }

#10

Thank You Hesters and Ben1nB1ack for thehelp.

#11

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?

#12

Just google please before you ask such questions.

But here you go, watch this: https://www.youtube.com/watch?v=SH7y8rrD1m8

#13

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

#14

Okay, Thank you mr. Hesters and LoL Stats

#15

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",
    "push_key":"token_retornado_pelo_firebase_tanto_no_android_quanto_ios"
  };

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

        this.http.post(this.URL_API + '/login/loginapp', this.dispositivo, {headers: headers})
          .subscribe(res => {
            resolve(res.json());
            console.log(res)
          }, (err) => {
            reject(err);
            console.log(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.