## Access Tokens vs Refresh Tokens

Medplum uses two types of tokens to manage authentication securely:

**Access Tokens** are short-lived JSON Web Tokens (JWTs) that grant access to Medplum APIs. Each access token contains essential information about the user's permissions and session details. Every API request must include a valid access token.

**Refresh Tokens** are long-lived credentials used to obtain new access tokens without requiring the user to log in again. These tokens are stored securely by client applications and are only transmitted when requesting a new access token.

### Requesting Refresh Tokens

Refresh tokens are not issued by default. To receive a refresh token, you must include one of the following scopes in your authentication request:

- `offline_access`
- `offline`

For example:

```ts
await medplum.startLogin({

email: 'admin@example.com',

password: 'password',

scope: 'openid offline_access',

});
```

```ts
await medplum.signInWithRedirect({

scope: 'openid offline_access',

});
```

## Configuring Token Lifetimes

### Default Token Lifetimes

| Token Type | Default Lifetime |
| --- | --- |
| Access | 3600 seconds (1 hour) |
| Refresh | 1209600 seconds (2 weeks) |

### Customizing Token Lifetimes

You can adjust token lifetimes by configuring your [`ClientApplication`](/content/docs/api/fhir/medplum/clientapplication/index.html) resource. Custom token lifetimes are useful when your application has specific security requirements or usage patterns.

Here's how to modify token lifetimes:

```ts
const clientApplication = {

resourceType: 'ClientApplication',

// Set access token lifetime to 2 hours (7200 seconds)

accessTokenLifetime: 7200,

// Set refresh token lifetime to 180 days

refreshTokenLifetime: 15552000,

};
```

### Managing Token Refresh with Grace Periods

The Medplum client includes a token refresh system that helps prevent service interruptions. The system uses a "grace period" to proactively refresh tokens before they expire.

### How Grace Periods Work

The grace period represents how long before expiration the client should attempt to refresh the token. By default, this is set to 5 minutes (300,000 milliseconds). For example, if your access token expires at 2:00 PM, the client will attempt to refresh it starting at 1:55 PM.

The Medplum client automatically handles token refresh in three scenarios:

1. Before making API requests when the token is within the grace period
2. When receiving a 401 Unauthorized response from the server
3. When your code explicitly requests a refresh

### Customizing the Grace Period

You can adjust the grace period when initializing the Medplum client:

```ts
// Initialize client with a 10-minute grace period

const customMedplum = new MedplumClient({

refreshGracePeriod: 600000, // 10 minutes in milliseconds

});

// You can also check authentication status with a custom grace period

if (!customMedplum.isAuthenticated(300000)) {

// Token will expire within 5 minutes

await customMedplum.refreshIfExpired();

}
```

## Best Practices for Token Management

1. **Use Short-Lived Access Tokens**  
Keep access token lifetimes short (1-2 hours maximum) to minimize the impact of token theft. The Medplum client's automatic refresh mechanism means you don't need long-lived access tokens for continuous operation.

2. **Leverage Automatic Token Refresh**  
The Medplum client handles token refresh automatically. Configure the grace period appropriately for your application's needs:

```ts
const bestPracticesMedplum = new MedplumClient({

refreshGracePeriod: 300000, // 5 minute grace period (default)

});
```

3. **Token Revocation**  
If you suspect a token has been compromised, revoke it immediately using the `/auth/logout` endpoint. Monitor your audit logs for suspicious activity that might indicate compromised tokens.

## Conclusion

For more advanced authentication scenarios, refer to our [Authentication reference](/content/docs/auth/index.html).
