Access Token for Service account for Cloud Speech API

12,031 views
Skip to first unread message

Ronald Ruijs

unread,
Oct 14, 2017, 11:04:15 AM10/14/17
to Google Cloud Developers

Hello,

While trying to get an access token for my Cloud Speech API service account as outlined here, I get errors in step 3 for getting a Bearer token.

Docs say to execute "gcloud auth application-default print-access-token"

I get response from gcloud: 
--
ERROR: (gcloud.auth.application-default.print-access-token) The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
--
The suggestion to use application-default-credentials is not applicable for me, as my development environment (Delph) does not seem to be supported.

Any idea what I am missing here?

Best regards,

Ronald

Kamran (Google Cloud Support)

unread,
Oct 14, 2017, 6:13:51 PM10/14/17
to Google Cloud Developers

Hello Ronald,

Try gcloud auth application-default login command to authenticate and generate Application Default Credential and then use gcloud auth application-default print-access-token command to obtain an access token.

Ronald Ruijs

unread,
Oct 15, 2017, 6:24:47 AM10/15/17
to Google Cloud Developers
Hi Kamran,

Thanks for you response! Unfortunately, when trying your suggestion using json file that was the result of creating a service account, I get another error response:
--
ERROR: (gcloud.auth.application-default.login) Invalid file format. See https://developers.google.com/api-client-library/python/guide/aaa_client_secrets Expected a JSON object with a single property for a "web" or "installed" application
--

I assume i cannot use Application Default Credentials, as my development environment (Delphi) is not supported. Is this correct?

Best regards,

Ronald


Op zaterdag 14 oktober 2017 17:04:15 UTC+2 schreef Ronald Ruijs:

Kamran (Google Cloud Support)

unread,
Oct 15, 2017, 12:31:52 PM10/15/17
to google-c...@googlegroups.com

For gcloud auth application-default login command you can use a file containing your own OAuth client ID to use to login. For creating a client ID, in the Credentials tab select the Create credentials drop-down list, and choose OAuth client ID. Otherwise, you can simply type and run gcloud auth application-default login command and use your own Google account to generate credentials.

Regarding your other question, I am not sure if you can call Application Default Credentials in a Delphi application code, however feel free to visit this article for some descriptions of Google Application Default Credentials, examples, and also some info about gcloud auth application-default login command.

Ronald Ruijs

unread,
Oct 15, 2017, 1:46:49 PM10/15/17
to Google Cloud Developers
Hi Kamran,

Then I would get an API key for my own gmail account, right?
My goal is to get a Google Cloud Speech API key for the service account I created for the speech project I created.
Or did I not interpret your answer correctly?

REgards, Ronald

Ronald Ruijs

unread,
Oct 15, 2017, 2:33:25 PM10/15/17
to Google Cloud Developers
Hi Kamran,

Just to clarify what I am trying to do: I follow the guidelines on https://cloud.google.com/speech/docs/auth

I want to obtain an access token for the service account I created for my Speech project.
I follow the steps for creating a bearer token, as documented:
---

Bearer tokens

If you're calling the Speech API directly, such as by making an HTTP request with cURL, you'll pass your authentication as a bearer token in an Authorization header. To obtain a bearer token using your service account:

  1. Install the gcloud command line tool.

  2. Authenticate to your service account, replacing KEY_FILE below with the path to your service account key file:

    gcloud auth activate-service-account --key-file=KEY_FILE

  3. Obtain an authorization token using your service account:

    gcloud auth application-default print-access-token

    The command returns an access token value.

---
Step 2 is OK:

C:\Users\ruijs\AppData\Local\Google\Cloud SDK>gcloud auth activate-service-account --key-file="C:\Users\ruijs\OneDrive\Ayuus\Google Cloud\Speech Recognition-ab032f696b4a.json"
Activated service account credentials for: [<my service account>@<my speech project>iam.gserviceaccount.com]


Step 3 returns an error:

C:\Users\ruijs\AppData\Local\Google\Cloud SDK>gcloud auth application-default print-access-token

ERROR: (gcloud.auth.application-default.print-access-token) The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.

What is going wrong here? I do not want to use application default credentials, just an access token.





Op zaterdag 14 oktober 2017 17:04:15 UTC+2 schreef Ronald Ruijs:

Ronald Ruijs

unread,
Oct 18, 2017, 3:04:56 PM10/18/17
to Google Cloud Developers
Hi Kamran,

Did you have time to have a look at issue regarding obtaining an access token for service account?

Regards, Ronald

Patrick Flynn

unread,
Oct 18, 2017, 4:23:18 PM10/18/17
to Ronald Ruijs, Google Cloud Developers
FYI if you're using the google-cloud-java vision API I believe it doesn't support the gcloud credentials and requires a service account configured to work.

--
You received this message because you are subscribed to the Google Groups "Google Cloud Developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-cloud-dev+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-cloud-dev/3865d547-d800-4d45-9631-1b07a353c328%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Kamran (Google Cloud Support)

unread,
Oct 23, 2017, 9:23:53 PM10/23/17
to Google Cloud Developers
Hi Ronald,

I've done some further investigation and I'll send a feedback to our documentation team to improve the Authenticating to the Cloud Speech API article.  In the meantime, you can use the following steps to get an authorization token using your service account:

1. Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to point to your service account key file.

export GOOGLE_APPLICATION_CREDENTIALS=PATH_TO_KEY_FILE

2. Obtain an authorization token using your service account:

gcloud auth application-default print-access-token


I hope this helps.

Sven Schubert

unread,
Nov 27, 2017, 9:04:37 AM11/27/17
to Google Cloud Developers
Hello,

I have several questions regarding the exact same tutorial about access to the Google Cloud Speech API. Everything works fine for me and I am able to obtain bearer access tokens using:

gcloud auth application-default print-access-token


Now here are my questions:
1.  Is there a limit of how many bearer access tokens can be possessed/issued at the same time (from a service account)?
2. Can theses bearer access tokens be used to do gRPC streaming requests to the Google Cloud Speech API?
3. Do you have a code example for C# how to use a bearer access token to establish a gRPC streaming request to the Google Speech API?
4. Can one bearer access token be used multiple times simultaniously? Meaning, while streaming A) is ongoing, can a second gRPC stream B) be established using the exact same bearer access token as for A) ?
5. Is it "safe" to distribute these bearer access tokens to our clients? Or what additional measures should be applied to prevent fraud usage of such a token. (Whereas I think the "risk" is limited to 3600 seconds and the scope defined, right?)
6. Is it possible to "see" somehow WHEN and HOW someone or something has used one of the bearer access tokens?

Many thanks for your help.

Ishwara Bhat

unread,
Jan 5, 2019, 9:19:40 AM1/5/19
to Google Cloud Developers
Please let me know if there is closure on this question. I am trying something similar.

I need to use JSON API to use speech API which accesses audio file in storage bucket. For storage bucket I anyway need OAuth token. For speech to text, I need the key.

I am trying to send something like this
URI : speech:recognize?key={KEY}

Then in the headers, I am adding the following. It does not work. (Authentication scope issue.). Could I get the access token to work for multiple scopes in the code? If so, only "Bearer TOKEN" would suffice for all the permission needs?

         request.Headers["Authorization"] = "Bearer " + m_Token;


Thanks for the kind attention.

Ishwar

Nathan (Cloud Platform support)

unread,
Jan 12, 2019, 9:50:56 AM1/12/19
to Google Cloud Developers
For Sven:

1. The amount of token to be process are related to the limits of the API, you can review them in this link.
2. Here is a code example of the use in C#
3. This is also related to the limits of the API
4. You can use a service account, review this link for a better view.
5. You can review the logs to see when it has been used

For Ishwar:

Use the transcribe.py with the command:
python transcribe.py gs://cloud-samples-tests/speech/brooklyn.flac
to use a file in GCS.

Can you provide more details on what do you mean by multiple scopes in the code?

Zaid Ahmad Khan

unread,
Apr 29, 2019, 3:21:15 PM4/29/19
to Google Cloud Developers
Hello Brother ,
                     I have done using streaming and authentication purpose I am using key json file downloaded from google account and put into local folder and passed the path ... Please see the application u can test the code in console app 



================================================================================
static async Task<int> StreamingMicRecognizeAsync(int seconds)
        {
            try
            {
                if (NAudio.Wave.WaveIn.DeviceCount < 1)
                {
                    Console.WriteLine("No microphone!");
                    return 0;
                }
                // var speech = SpeechClient.Create();
                string credentialsFilePath = @"D:\project\EY\testApp26April2019\khanzaid2490 (3)\key.json";
                GoogleCredential googleCredential;
                using (Stream m = new FileStream(credentialsFilePath, FileMode.Open))
                    googleCredential = GoogleCredential.FromStream(m);
                var channel = new Grpc.Core.Channel(SpeechClient.DefaultEndpoint.Host,
                    googleCredential.ToChannelCredentials());
                var speech = SpeechClient.Create(channel);
                //
                var streamingCall = speech.StreamingRecognize();
                // Write the initial request with the config.
                await streamingCall.WriteAsync(
                    new StreamingRecognizeRequest()
                    {
                        StreamingConfig = new StreamingRecognitionConfig()
                        {
                            Config = new RecognitionConfig()
                            {
                                Encoding =
                                RecognitionConfig.Types.AudioEncoding.Linear16,
                                SampleRateHertz = 16000,
                                LanguageCode = "en",
                            },
                            InterimResults = true,
                        }
                    });
                // Print responses as they arrive.
                Task printResponses = Task.Run(async () =>
                {
                    while (await streamingCall.ResponseStream.MoveNext(
                        default(CancellationToken)))
                    {
                        foreach (var result in streamingCall.ResponseStream
                            .Current.Results)
                        {
                            foreach (var alternative in result.Alternatives)
                            {
                                speechString = speechString + " " + alternative.Transcript;
                            }
                        }
                    }
                });
                // Read from the microphone and stream to API.
                object writeLock = new object();
                bool writeMore = true;
                var waveIn = new NAudio.Wave.WaveInEvent();
                waveIn.DeviceNumber = 0;
                waveIn.WaveFormat = new NAudio.Wave.WaveFormat(16000, 1);
                waveIn.DataAvailable +=
                    (object sender, NAudio.Wave.WaveInEventArgs args) =>
                    {
                        lock (writeLock)
                        {
                            if (!writeMore) return;
                            streamingCall.WriteAsync(
                                new StreamingRecognizeRequest()
                                {
                                    AudioContent = Google.Protobuf.ByteString
                                        .CopyFrom(args.Buffer, 0, args.BytesRecorded)
                                }).Wait();
                        }
                    };
                waveIn.StartRecording();
                Console.WriteLine("Speak now.");
                //button1
                await Task.Delay(TimeSpan.FromSeconds(seconds));
                // Stop recording and shut down.
                waveIn.StopRecording();
                lock (writeLock) writeMore = false;
                await streamingCall.WriteCompleteAsync();
                await printResponses;
            }catch(Exception ex)
            {
                return 0;
            }
            return 1;
        }


=========================================================
Reply all
Reply to author
Forward
0 new messages