# Authentication

## Overview

Headquarter uses OAuth2 authentication via Authentik. Users log in through their Authentik identity provider and receive a session cookie for authenticated access.

## How to Use

### Logging In

1. Navigate to the application
2. Click the **"Login"** button in the header
3. You will be redirected to **Authentik**
4. Enter your Authentik credentials
5. You will be redirected back to Headquarter, now logged in

### User Profile

After logging in, you can view your profile:

1. Click your **name** in the header
2. Select **"Profile"** from the dropdown
3. View and edit:
   - Display name
   - Email
   - Avatar (upload or change)

### Logging Out

1. Click your **name** in the header
2. Select **"Logout"**
3. Your session will be cleared
4. You will be redirected to the login page

## Authentication Flow

```
User → Click Login → Authentik Login → OAuth2 Callback → Session Cookie → Authenticated
```

### Technical Details

**Session Management:**
- Uses signed session cookies
- Cookie is `HttpOnly` and `Secure` (in production)
- Session expires after configurable TTL (default: 24 hours)

**OAuth2 Flow:**
1. User clicks login
2. Backend redirects to Authentik authorize URL
3. User authenticates with Authentik
4. Authentik redirects back with authorization code
5. Backend exchanges code for access token
6. Backend fetches user info from Authentik
7. Backend creates/updates local user record
8. Backend sets session cookie
9. User is authenticated

## API Reference

### Endpoints

- `GET /auth/login` - Initiate login (redirects to Authentik)
- `GET /auth/callback` - OAuth2 callback
- `GET /auth/me` - Get current user
- `POST /auth/logout` - Logout (clears session)

See [Auth API](../api/auth.md) for detailed endpoint documentation.

## Configuration

| Variable | Description | Default |
|----------|-------------|---------|
| `AUTHENTIK_DOMAIN` | Authentik server domain | - |
| `AUTHENTIK_CLIENT_ID` | OAuth client ID | - |
| `AUTHENTIK_CLIENT_SECRET` | OAuth client secret | - |
| `AUTHENTIK_APPLICATION_SLUG` | Application slug for URLs | `headquarter-web` |
| `SESSION_SECRET` | Session cookie signing secret | `change-me` |
| `SESSION_TTL_HOURS` | Session duration | `24` |

## Troubleshooting

### Login Loop

**Issue:** After logging in, you're redirected back to login
**Solution:** Check that cookie domain matches your domain configuration

### "Invalid State" Error

**Issue:** Error about invalid state parameter
**Solution:** Clear cookies and try again. If persistent, check Authentik configuration.

### Session Expired

**Issue:** "Session expired" message
**Solution:** Log in again. Session duration is configurable via `SESSION_TTL_HOURS`.

## Related Features

- [User Settings](settings.md) - Configure user preferences
