<!-- Source: https://www.wappi.dev/security/auth-keys -->

# Authenticated Users / API Keys

Auth Keys in Wappi provide secure authentication token management for user sessions and API access. These keys are automatically rotated and managed by Wappi to ensure maximum security for your application.

## How Auth Keys Work

Auth Keys are generated when users successfully authenticate through the Core_Login endpoint. These keys serve as session tokens that validate user identity and permissions for subsequent API requests.

- Generated automatically upon successful login
- Stored securely in the clients localStorage
- Automatically included in authenticated requests
- Rotated based on your configured schedule
- Validated on every protected endpoint

## Auth Key Configuration

### Environment Variables

```bash
# Current and previous auth keys for rotation
AUTH_KEY_CURRENT=your-current-auth-key-here
AUTH_KEY_PREVIOUS=your-previous-auth-key-here

# Environment setting affects key generation
ENVIRONMENT=prod
```

### wappi.json Configuration

```json
{
  "authRotation": "0 2 * * *",  // Daily rotation at 2 AM
  "apiKey": "your-api-key",
  "domains": "yourdomain.com, app.yourdomain.com"
}
```

## Auth Key Generation

Auth Keys are automatically generated when users log in through your Core_Login endpoint:

```typescript
// API/Core/Login/1.0.0/index.ts
export async function Core_Login_1_0_0(
  body: Body,
): Promise<Response> {
  try {
    if (!body) throw new Error('No Body')

    // ⌄⌄⌄⌄⌄ ADD CUSTOM LOGIN LOGIC HERE ⌄⌄⌄⌄⌄

    // ^^^^^ ADD CUSTOM LOGIN LOGIC HERE ^^^^^

    return {}
    // eslint-disable-next-line no-unreachable
  } catch (err) {
    console.error(err)
    return {
      error: err,
      message: err.message,
      devMessage: 'Fatal error in Core_Login_1_0_0. Investigate.',
      success: false,
    }
  }
}
```

## Automatic Key Rotation

Wappi automatically rotates auth keys based on your configured schedule to enhance security:

### Rotation Schedule

```json
{
  "authRotation": "*/30 * * * *",  // Every 30 minutes (high security)
  "authRotation": "0 */6 * * *",   // Every 6 hours (balanced)
  "authRotation": "0 0 * * *",     // Daily (standard)
  "authRotation": "0 0 * * 0",     // Weekly (low security)
  "authRotation": "0 0 1 * *",     // Monthly (low security)
  "authRotation": "0 0 1 */3 *",   // Every 3 months (low security)
  "authRotation": "0 0 1 */6 *",   // Every 6 months (low security)
  "authRotation": "0 0 1 1 *",     // Yearly (Jan 1) (low security)
}
```

### Rotation Process

1. 1. New auth key is generated automatically
2. 2. Current key moves to AUTH_KEY_PREVIOUS
3. 3. New key becomes AUTH_KEY_CURRENT
4. 4. Both keys remain valid during transition
5. 5. Previous key expires after next rotation
6. 6. Users are required to re-authenticated

## Using Auth Keys with wappi-fe

If you are using your API on a frontend application.
Auth Keys are automatically managed by wappi-fe.
Auth keys will be stored in a localStorage object
See [Frontend Integration > Authentication](https://www.wappi.dev/security/auth-keys)

## Auth Key Validation

Wappi automatically validates auth keys on protected endpoints.

Every endpoint will pass through the auth data that your **Core_Login_***** has returned.

This means that your auth key can contain any custom data you need for all endpoints.

For example. You have a API where a lot of endpoints require the validation of a "CompanyId". You can return this companyID in the auth token and it will be passed into every endpoint. Saving you an extra DB call.

Best practices: Don't pass through all user data in the auth key, it will make the auth key bloated. Just keep it simple and only include the fundamentals.

## AWS Secrets Manager Integration

For production environments, rotate auth keys with AWS Secrets Manager.

In your wappiConfig.json file. If you're using AWS. You can add:

```json
"serverProvider": "AWS",
```

If serverProvider is set to AWS. It will query your AWS secrets manager for your auth keys secret.

To customize your secret name and AWS region. Set the following Environment variables in your .env.example and .env files in production.

```bash
AWS_AUTH_KEY_SECRET_NAME="authKeys" # Default === "authKeys"
AWS_AUTH_KEY_SECRET_REGION="ap-southeast-2" # Default === "ap-southeast-2"
```

If you are using this method, it's recommended that you rotate your AWS keys at the same rate as your auth rotation setting in your wappiConfig.json file.
Use a lambda to rotate your secrets.

## Security Best Practices

- **Regular Rotation:** Set appropriate rotation intervals based on security requirements
- **Secure Storage:** Use AWS Secrets Manager
- **HTTPS Only:** Never transmit auth keys over unencrypted connections
- **Graceful Rotation:** Ensure smooth user experience during key rotation
- **Fallback Key:** Always maintain previous key for seamless transitions
- **Audit Logging:** Log all authentication events for security monitoring

URL: https://www.wappi.dev/security/auth-keys
