How to recognise an existing Google OAuth authentication made via Firebase and perform a Google Directory API request in Angular 2?

I want to use my existing authentication and be able to use that same authentication to perform a get request to the Google Directory API. Here’s my current code:

login() {
    this.firebaseRef = new Firebase('https://xxx.firebaseio.com');
    this.firebaseRef.authWithOAuthPopup("google", (error, authData) => {
        if (error) {
            console.log("Login Failed!", error);
        } else {
            console.log("Authenticated successfully with payload:", authData);
        }
    }, {
            scope: "https://www.googleapis.com/auth/admin.directory.user.readonly"
    });
}

getData() {
    // TO-DO
    // Recognise existing OAuth and perform a GET request to
    // https://www.googleapis.com/admin/directory/v1/users?domain=nunoarruda.com
}

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

You could leverage the getAuth method on the firebaseRef instance. Something like that:

getData() {
  var authData = this.firebaseRef.getData();
  var provider = authData.provider;
  // In your case provider contains "google"
}

See this documentation: https://www.firebase.com/docs/web/api/firebase/getauth.html.

Jason
Guest

I’ve found the solution. I need to use the current access token in the http request headers for the GET request. import {Http, Headers} from 'angular2/http'; getData() { // get access token let authData = this.firebaseRef.getAuth(); let oauthToken = authData.google.accessToken; console.log(oauthToken); // set authorization on request headers let headers = new Headers(); headers.append('Authorization', 'Bearer ' + oauthToken); // api request this.http.get('https://www.googleapis.com/admin/directory/v1/users?domain=nunoarruda.com',{headers: headers}).subscribe((res) => { console.log(res.json()); }); }