Before using the JavaScript fleet tracking library, make sure you are
familiar with and have set up Fleet Engine. For details, see
[Fleet Engine](https://developers.google.com/maps/documentation/mobility/fleet-engine).

This document shows how to enable authorization between the
web page app and Fleet Engine. Once your requests to Fleet Engine have
been set up with the correct authorization tokens, you'll be ready to
track a vehicle on a map.

## Set up authorization

Fleet Engine requires the use of **JSON Web Tokens** (JWTs) for API method calls
from **low-trust environments**: smartphones and browsers.

A JWT originates on your server, is signed, encrypted, and passed to the client
for subsequent server interactions until it expires or is no longer valid.

**Key details**

- Use [Application Default Credentials](https://google.aip.dev/auth/4110) to authenticate and authorize against Fleet Engine.
- Use an appropriate service account to sign JWTs. See [Fleet Engine serviceaccount](https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/service-accounts.md.txt#fleet_engine_service_account_roles) roles in **Fleet Engine Basics**.

### How does authorization work?

Authorization with Fleet Engine data involves both server-side and client-side
implementation.

#### Server-side authorization

Before you set up authentication and authorization in your Fleet tracking
application, your backend server must be able to issue JSON Web Tokens to your
Fleet tracking application for access to Fleet Engine. Your Fleet tracking application
sends these JWTs with its requests so Fleet Engine recognizes the requests as
authenticated and authorized to access the data in the
request. For instructions on server-side JWT implementation, see [Issue JSON Web
Tokens](https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt) under **Fleet Engine Essentials**.
To generate tokens from your server when implementing Fleet tracking, see the following:

<br />

- [General guidelines](https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt.md.txt#general_guidelines) for issuing JSON Web Tokens, including sections for both on-demand trips and scheduled tasks
- On-demand trips: [Example token for a backend server operation](https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt.md.txt#example_token_for_a_backend_server_operation)
- Scheduled tasks: [Example token to track all tasks and vehicles in the
  fleet](https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt#example_token_to_track_all_tasks_and_vehicles)

#### Client-side authorization

When you use the JavaScript Fleet tracking library, it requests a token from the server using an
authorization token fetcher. It does this when any of the following is true:

- No valid token exists, such as when the SDK hasn't called the fetcher on a
  fresh page load, or when the fetcher hasn't returned with a token.

- The token has expired.

- The token is within one minute of expiring.

Otherwise, the JavaScript Fleet tracking library uses the previously-issued, valid token and does not
call the fetcher.

### Create an authorization token fetcher

Create your authorization token fetcher using these guidelines:

- **The fetcher must return a data structure with two fields** , wrapped in a
  `Promise` as follows:

  - A string `token`.

  - A number `expiresInSeconds`. A token expires in this amount of time
    after fetching. The authentication token fetcher must pass the expiry
    time in seconds, from the time of fetching to the library as shown in
    the example.

- **The fetcher should call a URL on your server** to retrieve a token. This
  URL--the `SERVER_TOKEN_URL`--depends on your backend implementation. The
  following example URL is for the [sample app backend on GitHub](https://github.com/googlemaps/last-mile-fleet-solution-samples/tree/main/backend):

  - `https://SERVER_URL/token/fleet_reader`

#### Example - Create an authorization token fetcher

The following examples show how to create an authorization token fetcher:

### JavaScript

```javascript
async function authTokenFetcher(options) {
  // options is a record containing two keys called
  // serviceType and context. The developer should
  // generate the correct SERVER_TOKEN_URL and request
  // based on the values of these fields.
  const response = await fetch(SERVER_TOKEN_URL);
  if (!response.ok) {
    throw new Error(response.statusText);
  }
  const data = await response.json();
  return {
    token: data.Token,
    expiresInSeconds: data.ExpiresInSeconds
  };
}
```

### TypeScript

```typescript
function authTokenFetcher(options: {
  serviceType: google.maps.journeySharing.FleetEngineServiceType,
  context: google.maps.journeySharing.AuthTokenContext,
}): Promise<google.maps.journeySharing.AuthToken> {
  // The developer should generate the correct
  // SERVER_TOKEN_URL based on options.
  const response = await fetch(SERVER_TOKEN_URL);
  if (!response.ok) {
    throw new Error(response.statusText);
  }
  const data = await response.json();
  return {
    token: data.token,
    expiresInSeconds: data.ExpiresInSeconds,
  };
}
```

## What's next

- [Track a vehicle](https://developers.google.com/maps/documentation/mobility/operations/fleet-tracking/follow.md.txt)
- [View a fleet](https://developers.google.com/maps/documentation/mobility/operations/fleet-tracking/view-fleet.md.txt)