# Access tokens

Every request to the API carries an **access token** in its `Authorization` header. An access
token lasts five minutes. It is made from a refresh token: this page's login ([Logging in](/docs/login.md)), or
a script's offline token ([Creating a token for a script](/docs/login/script-token.md)).

## While you are logged in

The page makes access tokens by itself, whenever a request or **Copy with your token** needs
one and the one it has is about to end. **Get an access token** does the same on demand and
shows the exchange, if one was needed: the page answers from the token it has while that has
more than 30 seconds left.

**Copy** puts the token itself on the clipboard, for a tool of your own. It works until its end,
shown beside it.

## In a script

The client libraries do this for you. In the shell, the sample on the right does it: one
request with the refresh token saved in `reconnectchina-token`, whose answer holds the access
token. It puts that in `$TOKEN`, where the operation pages' curl commands read it, and when the
answer also holds a `refresh_token`, saves that in place of the one it sent.

The refresh token reaches curl on its standard input, not its command line, which other users of
the machine can read.

## Samples

Console programs that do what this page is about, logging in at the API's own /oauth. The Shell ones need curl and jq.

Every API host serves these pages for its own API. The samples are written for production, https://api.reconnectchina.org, as the pages are before they know their host. On another host, such as the sandbox, use that host instead: in curl's URL and the Shell samples' `login=` line, and as `server` for the Python and Node clients, which log in there too.

### Python

```python
from reconnectchina import Client, OfflineTokenFile

client = Client(
    tokens=OfflineTokenFile("reconnectchina-token"),
)
token = client.access_token()
```

### Shell

```sh
login=https://api.reconnectchina.org/oauth
answer=$(printf 'refresh_token=%s' "$(cat reconnectchina-token)" |
  curl -s "$login/token" -d client_id=reconnectchina-api -d grant_type=refresh_token -d @-)
new=$(echo "$answer" | jq -r '.refresh_token // empty')
if [ -n "$new" ]; then (umask 077 && echo "$new" > reconnectchina-token); fi
TOKEN=$(echo "$answer" | jq -r '.access_token // error(.error_description // .error)')
```

### Node

```js
import { readFile, writeFile } from "node:fs/promises";
import { Client } from "@reconnectchina/client";

const file = "reconnectchina-token";
const client = new Client({
  tokens: {
    load: async () => ({
      refreshToken: (await readFile(file, "utf8")).trim(),
      offline: true,
    }),
    save: (tokens) => tokens && writeFile(file, tokens.refreshToken),
  },
});
const token = await client.accessToken();
```
