Skip to content
This repository was archived by the owner on Jun 26, 2020. It is now read-only.

How to get the Token for API Call #106

Closed
Nicosoft opened this issue Sep 8, 2017 · 11 comments
Closed

How to get the Token for API Call #106

Nicosoft opened this issue Sep 8, 2017 · 11 comments

Comments

@Nicosoft
Copy link

Nicosoft commented Sep 8, 2017

Hi there,

I am trying to create a new method in /serverice/cognito.service.ts that returns the token JWT.
I need the token because I want to call a method in AWS Gateway. This method has a Authorization (Cognito User Pool).

So I wrote the following function in /serverice/cognito.service.ts
getToken() { let token = this.getCurrentUser().getSignInUserSession().getAccessToken().getJwtToken(); console.log('### TOKEN', token); return token; }
Unfortunately this generates an error:
screen shot 2017-09-08 at 4 50 45 pm

So my question is:
How do I correctly get the Token?

Thank for your help!

@Nr18
Copy link

Nr18 commented Sep 8, 2017

I added the generated api sdk to the project and using that for now, i would love to see this in a more native typescript/angular way.... but it's not my expertise.

@vbudilov vbudilov closed this as completed Sep 9, 2017
@Nicosoft
Copy link
Author

Thank you for your answer @vbudilov .

I use this function (getIdToken()) to get the token. Token that I provide in my call to the API gateway.
And guess what ... It works!

Here the service I created:

import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers} from '@angular/http';
import { Businessunit } from '../models/businessunit';
import { Observable } from 'rxjs/Observable';
import {Callback, CognitoUtil} from '../service/cognito.service';
import 'rxjs/Rx';

@Injectable()
export class BuService {

  private urlapi = 'https://###';
  private uri = 'businessunits';
  public idToken: string;

  constructor(
    private http: Http,
    public cognitoUtil: CognitoUtil) {
      this.cognitoUtil.getIdToken(new IdTokenCallback(this));
  }

  // Get all the divisions
  getBusinessunits(): Observable<Response> {
    
    let header = new Headers();
    header.append('Access-Control-Allow-Origin', '*');
    header.append('Content-Type', 'application/json');
    header.append('Authorization', this.idToken);
    let options = new RequestOptions({ headers : header });
    return this.http.get(this.urlapi + '/' + this.uri, options);
  }

}
export class IdTokenCallback implements Callback {
  constructor(public jwt: BuService) {
  }

  callback() {
  }

  callbackWithParam(result) {
      this.jwt.idToken = result;
  }
}

This documentation helped me a lot as well to know what token I needed to provide (Access Token or ID Token) and how to setup the AWS API Gateway.
http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html

Happy coding!

@Nr18
Copy link

Nr18 commented Sep 13, 2017

@Nicosoft thanks i'm implementing CloudFormation see #109 and afterwards i want to include a sample on how to use the API Gateway so i'm going to re-use some of your code if thats ok.

@kgilper
Copy link

kgilper commented Sep 21, 2017

@Nicosoft Thank you for sharing. The only issue I can see with this is that it will expire within an hour.

@Nicosoft
Copy link
Author

@kgilper you are right. If you stay on the same page, the token will expired.
If you know a better way please share it, otherwise I will when I find it!

@kgilper
Copy link

kgilper commented Oct 26, 2017

@Nicosoft you could do something like this. I ran it for a few hours calling the function using a timeout. The id token was refreshed as expected and it did not make extraneous calls to amazon.

import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import {Callback, CognitoUtil} from '../services/cognito.service';


@Injectable()
export class BuService {

  private urlapi = 'https://###';
  private uri = 'businessunits';
  public idToken: string;

  constructor(private http: Http, public cognitoUtil: CognitoUtil, public userParams: UserParametersService) { }

  getToken(): Observable<any> {
    return Observable.create(observer => {
      this.cognitoUtil.getIdToken(new IdTokenCallback(result => {
        observer.next(result);
      }));
    });
  }

  getBusinessunits(): Observable<Response> {
    return this.getToken().flatMap(token => {

      const header = new Headers();
      header.append('Access-Control-Allow-Origin', '*');
      header.append('Content-Type', 'application/json');
      header.append('Authorization', token);
      const options = new RequestOptions({headers: header});

      return this.http.get(this.urlapi + '/' + this.uri, options);
    });
  }
}

export class IdTokenCallback implements Callback {

  _valueReturnFunction: any = null;

  constructor(valueReturnFunction: any) {
    this._valueReturnFunction = valueReturnFunction;
  }

  callback() {
  }

  callbackWithParam(result) {
    this._valueReturnFunction(result);
  }
}

@Nicosoft
Copy link
Author

Nicosoft commented Nov 2, 2017

@kgilper , thanks for sharing. I am testing your version right now!

@kgilper
Copy link

kgilper commented Nov 3, 2017

@Nicosoft Did it work ok?

@Nicosoft
Copy link
Author

Nicosoft commented Nov 3, 2017

@kgilper , your version works better than my one.
I don't get the 'Expired Token' error message anymore.
Thank you again for sharing!

@kgilper
Copy link

kgilper commented Nov 3, 2017

@Nicosoft cheers to @vbudilov

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants