Home · Developers · Guides · API Authentication

APIs

API Authentication

Token auth, sessions, CSRF

The Nova Coder API supports token-based authentication with opaque server-side sessions.

Overview

The live authentication model is a single configured API token (api.token config or NOVACODER_API_TOKEN), enforced by TokenAuthMiddleware on all /api/* routes plus /graphql, /docs, /redoc, and /openapi.json. POST /api/auth/login issues an opaque, server-side session cookie (api/sessions.py) that expires per authentication.session_timeout and is revoked by /api/auth/logout.

2026-10-13 update: the dormant JWTAuth / PasswordAuth / OAuth2Handler / AdvancedAuthMiddleware helpers were removed from novacoder/api/auth.py, they were never wired into the request path (login issued a raw-token cookie, and no route decoded a JWT). The sections below describing them are retained for design history only; JWT_SECRET_KEY is no longer read or required. If multi-user JWT auth is ever implemented it should land as a deliberate feature, not dormant code guarded by the boot check.

Authentication Methods

Token-Based Authentication

The simplest authentication method using API tokens:

import httpx

# Using header
response = httpx.get("http://localhost:8000/api/status",
    headers={"x-api-token": "your-token-here"}
)

# Using Bearer token
response = httpx.get("http://localhost:8000/api/status",
    headers={"Authorization": "Bearer your-token-here"}
)

# Using the session cookie (obtained via POST /api/auth/login)
response = httpx.get("http://localhost:8000/api/status",
    cookies={"novacoder_session": "session-id"}
)

Note: there is no query-parameter authentication — ?token=… and ?api_key=… are not consulted by TokenAuthMiddleware (keeping tokens out of URLs/logs is deliberate).

JWT Authentication (removed, historical)

JSON Web Tokens provide stateless authentication:

from novacoder.api.auth import JWTAuth

# Create access token
token = JWTAuth.create_access_token({"user_id": "user123"})

# Use token in Authorization header
response = httpx.get("http://localhost:8000/api/status",
    headers={"Authorization": f"Bearer {token}"}
)

OAuth2 Authentication

OAuth2 provides standardized authorization:

from novacoder.api.auth import OAuth2Handler

# Create OAuth2 token
token = OAuth2Handler.create_oauth2_token("user123", ["read", "write"])

# Use token in Authorization header
response = httpx.get("http://localhost:8000/api/status",
    headers={"Authorization": f"Bearer {token}"}
)

Password Authentication

Password hashing and verification:

from novacoder.api.auth import PasswordAuth

# Hash password
hashed = PasswordAuth.hash_password("mypassword")

# Verify password
is_valid = PasswordAuth.verify_password("mypassword", hashed)

Configuration

Environment Variables

  • NOVACODER_API_TOKEN: API token for header/Bearer authentication
  • JWT_SECRET_KEY (no longer used, JWT helpers removed 2026-10-13)
  • ENVIRONMENT: Environment setting (development/staging/production)
  • NOVACODER_AUTHENTICATION__ENVIRONMENT: Authentication environment setting
  • NOVACODER_AUTHENTICATION__COOKIE_SECURE: Cookie secure flag (true/false)
  • NOVACODER_AUTHENTICATION__COOKIE_SAMESITE: Cookie SameSite policy (lax/strict/none)
  • NOVACODER_AUTHENTICATION__SESSION_TIMEOUT: Session timeout in seconds (default: 3600)

Token Configuration

Configure token authentication in the application config:

from novacoder.config.settings import AppConfig

config = AppConfig(api={"token": "your-api-token"})

Authentication Configuration

The authentication system uses a dedicated configuration section:

from novacoder.config.settings import AppConfig, AuthenticationConfig

config = AppConfig(
    api={"token": "your-api-token"},
    authentication={
        "environment": "development",
        "cookie_secure": False,
        "cookie_httponly": True,
        "cookie_samesite": "lax",
        "session_timeout": 3600,
        "rate_limit_enabled": True,
        "rate_limit_requests": 100,
        "rate_limit_period": 60
    }
)

Or configure via config/defaults.yaml:

authentication:
  environment: development
  cookie_secure: false
  cookie_httponly: true
  cookie_samesite: lax
  session_timeout: 3600
  rate_limit_enabled: true
  rate_limit_requests: 100
  rate_limit_period: 60

Security Best Practices

  1. Use HTTPS: Always use HTTPS in production
  2. Secure Secret Keys: Use strong, random secret keys
  3. Token Expiration: Set appropriate token expiration times
  4. Token Rotation: Implement token rotation for long-lived tokens
  5. Scope Limitation: Use OAuth2 scopes to limit access
  6. Environment-Aware Security: Use appropriate security settings per environment
  7. Session Timeout: Implement session timeout for automatic logout
  8. Cookie Security: Use HttpOnly and SameSite flags for cookies
  9. Rate Limiting: Implement rate limiting on authentication endpoints
  10. CSRF Protection: Use CSRF tokens for state-changing operations
  11. Audit Logging: Track authentication attempts and failures

Session Management

Session Cookies

The authentication system uses session cookies for web interface authentication:

  • Cookie Name: novacoder_session
  • Cookie Format: token:timestamp (e.g., novacoder-secure-token-2024:1785273593)
  • HttpOnly: Prevents JavaScript access to cookies
  • SameSite: lax for better cross-site compatibility
  • Secure: Environment-aware (false in development, true in production)
  • Max-Age: Configurable session timeout (default: 3600 seconds)

Session Timeout

Sessions automatically expire after the configured timeout:

# Session timeout is checked on each authentication status check
# Expired sessions return authenticated: false with diagnostic information

Session Diagnostics

The /api/auth/status endpoint provides diagnostic information:

{
  "authenticated": true,
  "success": true,
  "diagnostics": {
    "has_session_token": true,
    "app_running": true,
    "token_configured": true,
    "cookie_present": true,
    "session_expired": false,
    "session_age": 123,
    "session_timeout": 3600
  }
}

Environment-Aware Security

The authentication system automatically adapts security settings based on the environment:

Development Environment

  • Cookie secure flag: false (allows HTTP)
  • Detailed error messages enabled
  • Full diagnostic information available
  • Authentication bypass: When authentication.environment is set to development, API authentication is bypassed for easier testing. This allows API endpoints to be called without tokens in development mode.

Production Environment

  • Cookie secure flag: true (requires HTTPS)
  • Generic error messages for security
  • Limited diagnostic information
  • Strict authentication: API tokens are required for all endpoints except /api/health.

Environment Detection

The system detects the environment using:

  • ENVIRONMENT environment variable
  • URL detection (localhost/127.0.0.1 for development)
  • Configuration file settings

API Endpoints

Login Endpoint

POST /api/auth/login

Authenticate with API token and create session.

Request Body:

{
  "token": "your-api-token"
}

Response:

{
  "success": true,
  "message": "Login successful",
  "authenticated": true,
  "session_timeout": 3600
}

Response Headers:

set-cookie: novacoder_session=token:timestamp; HttpOnly; Max-Age=3600; Path=/; SameSite=lax

Logout Endpoint

POST /api/auth/logout

Clear session and logout by invalidating the session cookie.

Response:

{
  "success": true,
  "message": "Logout successful",
  "authenticated": false
}

Cookie Deletion: The logout endpoint sends a Set-Cookie header to clear the session cookie:

set-cookie: novacoder_session=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/; SameSite=lax

Implementation Details:

  • Stateless design - no server-side session state to clear
  • Cookie deletion via Set-Cookie header with past expiration
  • Environment-aware cookie attributes (secure flag adapts to environment)
  • Client must handle UI state changes after logout

Status Endpoint

GET /api/auth/status

Check authentication status with diagnostics.

Response:

{
  "authenticated": true,
  "success": true,
  "diagnostics": {
    "has_session_token": true,
    "app_running": true,
    "token_configured": true,
    "cookie_present": true,
    "session_expired": false
  }
}

Implementation

Token enforcement lives in TokenAuthMiddleware (novacoder/api/app.py); session issue/expiry/revocation in novacoder/api/sessions.py and novacoder/api/routes_auth.py; boot-time environment validation in novacoder/api/auth.py (validate_auth_environment, warns on missing token in development, refuses to boot unauthenticated otherwise).

Dependency Handling

The live auth path has no optional dependencies, opaque session ids are secrets.token_urlsafe values, so no PyJWT/passlib requirement exists. (The dormant helpers previously documented here were removed 2026-10-13.)

Web UI Integration

The Authentication system is fully integrated into the Nova Coder Web UI with a dedicated "Authentication" navigation item under the Administration section.

Authentication UI Features

The Authentication UI provides:

  • Authentication Status Display: Shows whether the user is authenticated
  • Success Status Display: Shows the success status of the authentication check
  • Login Button: Displays a login button when the user is not authenticated
  • Session Management: Tracks authentication session status

API Endpoints Used

The Authentication UI integrates with the following API endpoint:

  • GET /api/auth/status - Check authentication status

UI Navigation

Access the Authentication UI by:

  1. Navigate to the Administration section in the sidebar
  2. Click on "Authentication"
  3. The UI displays authentication status in a grid layout

JavaScript Integration

The Authentication UI is implemented in novacoder/web/static/js/app.js with the following functions:

  • renderAuth() - Main render function for the Authentication page
  • loadAuthData() - Load and display authentication status
  • toggleAuth() - Toggle authentication state (login/logout)

Response Handling

The UI handles API responses according to the actual response structure from the auth status endpoint:

  • Auth Status Response: Expects authenticated (boolean) and success (boolean) fields
  • Authenticated Field: Indicates whether the user is currently authenticated
  • Success Field: Indicates whether the authentication check was successful

Display Format

The Authentication UI displays authentication information in a grid layout with:

  • Authenticated Status: Yes/No indicator with color coding
  • Success Status: Yes/No indicator
  • Login Button: Displayed when not authenticated, hidden when authenticated

Session Management

The Authentication UI uses session cookies for authentication:

  • Session Cookie: novacoder_session cookie stores the authentication token
  • Token Validation: Compares session token with configured API token
  • Auto-Refresh: Authentication status is checked on page load and navigation

Source: wiki/api-authentication.md · rendered 2026-11-10