invoke-ai/InvokeAI · error · HTTPException
Invalid or expired token
Error message
Invalid or expired token
What it means
After extracting the raw token, refresh_media_cookie calls get_token_remaining_seconds(token); if it returns None the token's signature is invalid or it has expired, so a 401 'Invalid or expired token' is raised and no media cookie is set.
Source
Thrown at invokeai/app/api/routers/auth.py:322
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
Returns:
UserDTO containing user information
Raises:View on GitHub (pinned to 0b6a024f2f)
Solutions
- Re-authenticate via /auth/login to get a fresh token, then retry
- Use remember_me on login for a longer token lifetime (TOKEN_EXPIRATION_REMEMBER_ME)
- If tokens break after every restart, configure a stable secret key for the server
- Sync server/client clocks if skew is the cause
Example fix
// before
await refreshMediaCookie(staleToken); // 401 invalid or expired
// after
const { access_token } = await api.post('/auth/login', creds);
await refreshMediaCookie(access_token); Defensive patterns
Strategy: try-catch
Validate before calling
# decode JWT locally to check expiry before the call
import time, base64, json
def token_expired(token: str) -> bool:
payload = json.loads(base64.urlsafe_b64decode(token.split('.')[1] + '=='))
return payload.get('exp', 0) < time.time() Type guard
def is_fresh_token(token: str) -> bool:
import time, base64, json
try:
payload = json.loads(base64.urlsafe_b64decode(token.split('.')[1] + '=='))
return payload.get('exp', 0) >= time.time()
except Exception:
return False Try / catch
try:
resp = requests.post(f'{base}/auth/media-cookie', headers={'Authorization': f'Bearer {token}'})
resp.raise_for_status()
except requests.HTTPError as e:
if e.response.status_code == 401 and 'expired' in e.response.json().get('detail', ''):
token = relogin() # refresh token, then retry once Prevention
- Refresh the token proactively before its exp passes (use remember_me for longer TTL)
- Set a stable JWT secret so restarts don't invalidate tokens
- Wrap authenticated calls in a 401 -> re-login -> retry-once interceptor
- Check clock sync if tokens seem to expire early
When it happens
Trigger: Calling the media-cookie refresh endpoint with a Bearer token that is expired (past TOKEN_EXPIRATION_NORMAL / REMEMBER_ME) or has an invalid signature (e.g. JWT secret changed after restart, token from a different install).
Common situations: Long-lived tab/browser session outliving the token TTL; server restarted with a different secret key invalidating old tokens; copying a token between environments; clock skew.
Understand the failure class
- Authentication and authorization failures — expired tokens, bad credentials, and missing scopes.
Related errors
- Incorrect email or password
- Authentication required
- JWT secret not found in database. This should have been crea
- JWT secret has not been initialized. Call set_jwt_secret() d
AI-assisted analysis of invoke-ai/InvokeAI@0b6a024f2f (2026-08-29).
Data as JSON: /api/errors/8052400c6890bf1e.
Report an issue: GitHub.