invoke-ai/InvokeAI · error · HTTPException

Authentication required

Error message

Authentication required

What it means

refresh_media_cookie needs the raw Bearer token to set as the media cookie value. Although CurrentUserOrDefault normally guarantees credentials exist (it 401s otherwise), this defensive 401 fires if credentials are None — i.e. the request reached the handler without a parseable Bearer token.

Source

Thrown at invokeai/app/api/routers/auth.py:317

    expiry anyway.

    Returns:
        MediaCookieResponse indicating the cookie was set. In single-user mode the
        media routes don't require authentication, so this is a successful no-op.

    Raises:
        HTTPException: 401 if the Bearer token is missing, invalid, or expired, or
        the user no longer exists or is inactive (raised by the auth dependency).
    """
    config = ApiDependencies.invoker.services.configuration
    if not config.multiuser:
        return MediaCookieResponse(success=True)

    # CurrentUserOrDefault has already validated the Bearer token (signature, expiry,
    # user exists and is active) — in multiuser mode it 401s otherwise, so credentials
    # cannot be None here. The raw token is still needed as the cookie value.
    if credentials is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Authentication required")

    token = credentials.credentials
    remaining = get_token_remaining_seconds(token)
    if remaining is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or expired token")

    _set_media_cookie(request, response, token, remaining)
    return MediaCookieResponse(success=True)


@auth_router.get("/me", response_model=UserDTO)
def get_current_user_info(
    current_user: CurrentUser,
) -> UserDTO:
    """Get current authenticated user's information.

    Args:
        current_user: The authenticated user's token data

View on GitHub (pinned to 0b6a024f2f)

Solutions

  1. Send a valid 'Authorization: Bearer <token>' header obtained from /auth/login
  2. Re-login to get a fresh token, then retry the refresh call
  3. Check any reverse proxy isn't stripping the Authorization header
  4. Fix the client to keep the token before invoking this endpoint

Example fix

// before
await api.post('/auth/media-cookie'); // no auth header
// after
await api.post('/auth/media-cookie', { headers: { Authorization: `Bearer ${token}` } });
Defensive patterns

Strategy: type-guard

Validate before calling

token = get_stored_token()
if not token:
    token = relogin()  # obtain a fresh Bearer token before calling the endpoint

headers = {'Authorization': f'Bearer {token}'}

Type guard

def has_bearer_token(headers: dict) -> bool:
    auth = headers.get('Authorization', '')
    return auth.startswith('Bearer ') and len(auth) > len('Bearer ')

Try / catch

try:
    resp = requests.post(f'{base}/auth/media-cookie', headers=headers)
    resp.raise_for_status()
except requests.HTTPError as e:
    if e.response.status_code == 401:
        relogin_and_retry()

Prevention

When it happens

Trigger: GET/POST to the media-cookie refresh endpoint with no Authorization header, a malformed 'Authorization: Bearer' header (empty token), or a security override that skipped full token validation.

Common situations: Client deleted its stored token but still calls the refresh endpoint; proxy stripping the Authorization header; sending the cookie instead of the Bearer header; race after token storage cleared.

Understand the failure class

Related errors


AI-assisted analysis of invoke-ai/InvokeAI@0b6a024f2f (2026-08-29). Data as JSON: /api/errors/63dc58d340fbf35c. Report an issue: GitHub.