> For the complete documentation index, see [llms.txt](https://docs.appfarm.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.appfarm.io/how-to/integrations/retrieve-bearer-token-from-google-cloud.md).

# Retrieve a Bearer token from Google Cloud

This guide builds a [Flow](https://docs.appfarm.io/reference/flows.md) action that gets a Bearer token from Google Cloud and stores it in a secret, and a schedule that keeps the token fresh.

### Step 1

To start this guide, you'll need a Service Account JSON file from Google Cloud. If you don't have it yet, please take a look at this guide from Google to set everything up in Google Cloud and retrieve the file.

{% embed url="<https://cloud.google.com/docs/authentication/getting-started>" %}

You also need a service account in Appfarm Create to run the schedule, with a role that is allowed to update the token secret. You give that permission in step 2.

### Step 2

Log in to Appfarm Create. Go to **Security** > **Secrets**, and add the following secrets to the Secret Store.

* **Google API Client Email:** Secret type should be string. Value be found in the Service Account JSON file as `client_email`. The email should look something like this:\
  `[name]@[project_id].iam.gserviceaccount.com`
* **Google SA Private Key:** Secret type should be a string. Value can be found in the Service Account JSON file as `private_key`. Include both the beginning and end statements.
* **Google API Token:** Secret has to be Environment Specific, and secret type should be string. Leave all values empty.

Then go to **Security** > **Permissions** > **Advanced**. Under **Update Secret from Service**, allow the role of the service account that will run the schedule to update **Google API Token**.

### Step 3

Go to **Flows**, and select the Flow you want to use (or create a new one). Then, create a new action, which will be used to fetch the Google API Token. You may name the Action "GetGoogleAPIToken".

### Step 4

In the action, go to **Action data** and add an action variable named `Bearer token` with Data Type String.

### Step 5

Go back to **Logic**, and add a new Action Node "Web Request". Set the following properties:

* **Base URL:** `https://oauth2.googleapis.com`
* **Path:** `/token`
* **Method:** POST
* **Body Type:** URL-encoded
* **Body Content:** Add two form data entries:
  * **Key:** `grant_type`, **Value:** `urn:ietf:params:oauth:grant-type:jwt-bearer`
  * **Key:** `assertion`, **Value:** a function that builds a signed JWT (see below)

In the function editor for the `assertion` value, add the two secrets "Google API Client Email" and "Google SA Private Key" as Function Parameters, as well as the library "jsonwebtoken". Parameter names should be `googleAPIClientEmail`, `googleSAPrivateKey` and `jsonwebtoken` respectively. Then, add the following code:

```
const now = new Date().getTime() / 1000;
const oneHour = 60 * 60;
const expireTime = now + oneHour;

const claimSet = {
   iss: googleAPIClientEmail,
   iat: now,
   sub: googleAPIClientEmail,
   exp: expireTime,
   scope: "https://www.googleapis.com/auth/bigquery",
   aud: "https://oauth2.googleapis.com/token"
}

// The secret is stored on one line, so turn the \n sequences from the JSON file back into line breaks
const privateKey = googleSAPrivateKey.replace(/\\n/g, '\n');

return  jsonwebtoken.sign(claimSet, privateKey, {algorithm: 'RS256'})
```

The `replace` line matters: a secret value is a single line, so the line breaks in `private_key` arrive as the two characters `\n`. Without the `replace`, signing fails with a `DECODER routines::unsupported` error.

Click "OK" to save the changes.

In the Result Mapping, set Data Source to `Action Variables`. In the value field on the property "Bearer token", write `access_token`.

### Step 6

Add a new Action Node "Update Secret". Set "Secret" to Google API Token, and Data Bind the value to the action variable `Bearer token`.

### Run the action on a schedule

Now everything is set up to retrieve and save the Bearer token from Google Cloud. The token expires after one hour, so run the action on a schedule. Under **Triggers** in the action, click **set up a schedule**, enter a cron expression in **Schedule** that runs more often than once an hour (for example `*/30 * * * *`), select the service account from step 1 as **Service Account**, and select **Enabled**. See [Schedules](https://docs.appfarm.io/reference/flows/schedules.md) for details.

If everything is set up correctly, the token will be added as a value in your secret "Google API Token" each time the schedule runs.

{% hint style="info" %}
**Good to know**

A test run from Flow DevTools runs as your own user, not as the service account. The **Update Secret** node can then fail with "User does not have sufficient permissions". Check the secret after a scheduled run instead, which uses the service account's role.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.appfarm.io/how-to/integrations/retrieve-bearer-token-from-google-cloud.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
