Search code examples
androidgoogle-speech-apigoogle-cloud-speech

Getting a Google Speech API access token for a production Android app


I'm using the Google Speech API in an Android app. The README states: In this sample, we load the credential from a JSON file stored in a raw resource folder of this client app. You should never do this in your app. Instead, store the file in your server and obtain an access token from there.

Are there any samples regarding how to properly obtain an access token for a production app?

From what I've gathered, it seems that I can use Application Default Credentials provided via Compute Engine or GAE, but I have no idea how to actually respond with an access token to my app.


Solution

  • I'm the author of the sample.

    Here's the part that should be on the server side. Basically, you have to store the JSON file securely on your server side, and fetch a new access token when you get a request from your mobile app. Mobile app should always talk with your server to get an access token. This way, you don't need to put your service account key in the APK.

            // In response to a request from a mobile client
    
            // Open the JSON file stored on the server side.
            final InputStream stream = ...;
            try {
                // Initialize the credentials
                final GoogleCredentials credentials =
                    GoogleCredentials.fromStream(stream)
                        .createScoped(SCOPE);
                // Fetch a new access token.
                final AccessToken token = credentials.refreshAccessToken();
    
                // Return the token to the mobile app.
    
            } catch (IOException e) {
    
                // Maybe report this as an HTTP error.
    
            }
    

    If you don't use Java on your server side, you can find a client library for the language you use at Google Cloud Client Libraries.

    Refer to Google Cloud Platform Auth Guide for basics about how to send requests from your backend to the API.