How to connect to Cuba-Platform Rest API with OAuth2 in Angular2 and Ionic 2

Hi. I wanted to share the code, how to connect to Cuba-Platform REST Api with OAuth2 in Angular 2 and Ionic 2 TypeScript.
So here it comes:


import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the AuthService provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class AuthService {
  ourcode;
  accesstoken;
  tokentype;
  expires_in;
  scope;

  constructor(public http: Http) {
    console.log('Hello AuthService Provider');
  }

  getAccessToken() {
  let client_id = 'client';
  let client_secret= 'secret';
  var basicheader = btoa(client_id + ':' + client_secret);
  
  var headers = new Headers();
  
  headers.append('authorization', 'Basic '+ basicheader);
  headers.append('cache-control', 'no-cache');
  headers.append('content-type', 'application/x-www-form-urlencoded; charset=utf-8');
  
  var tokendata = 'grant_type=password&username=admin&password=admin';
  
  this.http.post('http://localhost:8080/app/rest/v2/oauth/token', tokendata, {headers: headers}).subscribe((data) => {
    
    
    this.accesstoken = data.json().access_token;
    this.tokentype = data.json().token_type;
    this.expires_in = data.json().expires_in;
    this.scope = data.json().scope;

    console.log(this.accesstoken + " " + this.tokentype + " - " + this.expires_in + " - " + this.scope );
    //this.router.navigate(['/books']);
  })
}

}

Create a service in Angular2 (ng generate service AuthService) or provider in Ionic 2 (ionic generate provider AuthService).
Copy and paste the code from here and into the service file.

Thanks for sharing. here is a PHP sample:


<?php
$url = 'http://localhost:8080/app/rest/v2/oauth/token';
$data = array('grant_type' => 'password', 'username' => 'admin', 'password' => 'admin');

$client = "client";
$secret = "secret";

$header = "Content-type: application/x-www-form-urlencoded\r\n" . "Authorization: Basic " . base64_encode("$client:$secret");


// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => $header,
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
var_dump($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

?>
1 Like