Skip to content

Auth: Unify session and API key authentication#1513

Open
william-p wants to merge 3 commits intoapache:devfrom
william-p:refactorApiAuth
Open

Auth: Unify session and API key authentication#1513
william-p wants to merge 3 commits intoapache:devfrom
william-p:refactorApiAuth

Conversation

@william-p
Copy link

@william-p william-p commented Mar 6, 2026

Context

Until now, the REST API routes (/answer/api/v1) only accepted session-based user authentication. API keys were restricted to MCP endpoints. This PR unifies both authentication mechanisms to allow access to REST routes via an API token in addition to the classic session.

(Issue: #1508)

Changes

New unified AuthSessionOrAPIKey middleware

A new middleware replaces the MustAuthAndAccountAvailable and AuthAPIKey middlewares on the relevant routes. It first attempts session-based authentication; if that fails, it falls back to API key authentication via the Authorization header. This allows programmatic clients (scripts, integrations, external tools) to use the same REST endpoints as the web interface.

API key authentication service refactoring

The AuthAPIKey method on AuthService has been renamed to GetAPIKeyInfo and now returns the full APIKey entity (including the associated UserID) instead of a simple boolean. This allows the middleware to resolve the user linked to the key and inject it into the request context, exactly as a classic session would.

Enriched dependency injection

The AuthUserMiddleware now receives userRepo and userRoleService to load the full user profile associated with an API key and verify their status (active, suspended, deleted) as well as email verification.

User status validation factoring

The user status verification logic (email verified, account suspended/deleted) has been extracted into a reusable validateUserStatus method, eliminating duplication across the different middlewares.

Tests

  • Middleware unit tests: coverage of nominal cases (valid session, valid read-write API key, read-only API key on GET), as well as error cases (invalid key, suspended/deleted user, insufficient scope).
  • Service unit tests: validation of GetAPIKeyInfo behavior (valid key, read-only key on GET vs non-GET request, non-existent key).

Impact

  • REST routes under /answer/api/v1 and MCP routes now accept either a session or an API key interchangeably.
  • No behavior change for existing users who authenticate via session.
  • API keys still respect their scope (read-only / read-write).

@william-p william-p marked this pull request as ready for review March 6, 2026 21:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant