# Authentication

Authentication in the therappai API is handled using **JWT-based bearer tokens**. You’ll authenticate once with a user’s credentials, receive tokens, and include them in all subsequent requests.

This page explains how access tokens work, how to refresh them, and what headers to send.

***

### **How authentication works**

1. A user signs up or logs in.
2. The API returns an **access token** and a **refresh token**.
3. You send the **access token** in the `Authorization` header for all authenticated endpoints.
4. When the access token expires, you use the refresh token to obtain a new one.

This allows secure, stateless sessions without storing credentials.

***

### **Access Tokens**

The **access** token is required for all API calls that involve user data, sessions, or protected resources.

It is sent using the standard bearer header:

```
Authorization: Bearer ACCESS_TOKEN_HERE
```

#### Key properties

* Short-lived
* Required for all authenticated requests
* Encodes the user identity and permissions

If the access token is missing or expired, the API will return `401 Unauthorized`.

***

### **Refresh Tokens**

The **refresh** token is used to generate a new access token without requiring the user to log in again.

To refresh:

```
POST /refresh/
```

Send the refresh token in the request body. The response returns a new access token.

#### Key properties

* Long-lived
* Must be stored securely (do not expose in client-side code)
* Only used to request a new access token

***

### **Required Headers**

Most authenticated API requests must include:

```
Authorization: Bearer ACCESS_TOKEN_HERE
Content-Type: application/json
```

If uploading files (e.g., updating profile picture), use:

```
Content-Type: multipart/form-data
```

***

### **Session Rules**

To keep sessions secure and predictable:

* Access tokens expire for safety — always be ready to refresh.
* Refresh tokens should be stored securely (e.g., encrypted storage, secure cookies).
* If a refresh token is invalid or expired, the user must log in again.
* Do not expose tokens in logs, URLs, or frontend bundle code.

***

### **Common authentication errors**

| Error                       | Meaning                               | How to fix                           |
| --------------------------- | ------------------------------------- | ------------------------------------ |
| `401 Unauthorized`          | Missing or invalid access token       | Send the correct token in the header |
| `403 Forbidden`             | Token is valid but not allowed access | Check the endpoint requires login    |
| `419 Token expired`         | Access token expired                  | Refresh using `/refresh/`            |
| `400 Invalid refresh token` | Refresh token no longer valid         | Re-login required                    |
