0
votes

I have created a unity application to sign-in using google and access google-classroom api. The sign-in is successful and the scope allows access to the courses too.

Question: How to query the google classroom api after signing in with firebase. endpoint : https://classroom.googleapis.com/v1/courses/105459102203 Method : GET Parameter : CourseId which I already have

BearerToken : How to retrieve this from firebase?

When I try using auth-code and/or idToken it gives the following error:

{ "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED" } }

Thanks in advance.

1

1 Answers

1
votes

There are many ways to make a succesfully API request via firebase Auth, in particulary to Google Classroom API:

  1. The hard way is to create a HttpInterceptor for the firebase.UserCredentials and pass it on headers of every HttpRequest, somethis like this:
headers: new HttpHeaders(
      {
        'Content-Type': 'application/json',
        Authorization: `Bearer [${this.user$.AccessToken}]`
      })

this is what I call the hard way because you have to ensure to pass and refresh tokens y every API services.

  1. Use the javascript library "gapi" to login the client, and then use the token response as credential to login in Firebase. This aproach creates a pure OAuth2 login that serves to Firebase and further Google APIs requests, as follows:
declare var gapi;
/** Initialize Google API Client */
initClient(): void {
  gapi.client.init({
    apiKey: environment.firebaseConfig.apiKey,
    clientId: environment.firebaseConfig.clientId,
    discoveryDocs: environment.firebaseConfig.discoveryDocs,
    scope: environment.firebaseConfig.scope,
    });
}
/** Do a OAuth login and then pass it to a FirebaseAuth service */
  async login() {
      const googleAuth = gapi.auth2.getAuthInstance();
      const googleUser = await googleAuth.signIn();
      const token = googleUser.getAuthResponse().id_token;
      const credential = firebase.auth.GoogleAuthProvider.credential(token);
      await this.afAuth().signInAndRetrieveDataWithCredential(credential);
  }
/** Then you're ready to make a request*/
/**
   * Lists all course names and ids.
   * Print the names of the first 10 courses the user has access to. If
   * no courses are found an appropriate message is printed.
   */
  listCourses() {
    this.courses$ = 
      gapi.client.classroom.courses.list({pageSize=10;}).then(response => {
      return from<Course[]>(response.result.courses);
    });
  }