Search code examples
androidgoogle-cloud-functionsgoogle-speech-api

Is it possible to generate an access token for a Google Cloud Platform API in a Cloud Function?


I currently have an Android app which utilizes the Google Speech-to-Text library. During development, I have a Service Account JSON file in /res/raw/, which I use as credentials for the API.

I've added Firebase Auth UI to the app, and I now want to provide credentials to the Speech-to-Text API through Firebase. Is that possible using Cloud Functions (generate a token based on the Firebase Service Account), if so, how do I obtain it?

I could not find any documentation related to generating access tokens within a Cloud Function.


Solution

  • Node is the language with which I'm the less confortable. Here a minimal example for generating an access token based on the Cloud Function identity

    const express = require('express');
    const app = express();
    
    const {GoogleAuth} = require('google-auth-library');
    const auth = new GoogleAuth()
    app.get('/', async (req, res) => {
        res.send(await auth.getAccessToken());
    });
    
    const port = process.env.PORT || 8080;
    app.listen(port, () => {});
    

    You have to add google-auth-library in your dependencies

    There is no authentication (you have to be sure that the requester is authorized, I mean your user logged in your Android App, I assume with firebase auth) and the access token is returned in plain text (no json format).

    I think you can adapt this.