{"record":{"id":"63dc58d340fbf35c","repo":"invoke-ai/InvokeAI","slug":"authentication-required-63dc58","errorCode":null,"errorMessage":"Authentication required","messagePattern":"Authentication required","errorType":"http","errorClass":"HTTPException","httpStatus":401,"severity":"error","filePath":"invokeai/app/api/routers/auth.py","lineNumber":317,"sourceCode":"    expiry anyway.\n\n    Returns:\n        MediaCookieResponse indicating the cookie was set. In single-user mode the\n        media routes don't require authentication, so this is a successful no-op.\n\n    Raises:\n        HTTPException: 401 if the Bearer token is missing, invalid, or expired, or\n        the user no longer exists or is inactive (raised by the auth dependency).\n    \"\"\"\n    config = ApiDependencies.invoker.services.configuration\n    if not config.multiuser:\n        return MediaCookieResponse(success=True)\n\n    # CurrentUserOrDefault has already validated the Bearer token (signature, expiry,\n    # user exists and is active) — in multiuser mode it 401s otherwise, so credentials\n    # cannot be None here. The raw token is still needed as the cookie value.\n    if credentials is None:\n        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=\"Authentication required\")\n\n    token = credentials.credentials\n    remaining = get_token_remaining_seconds(token)\n    if remaining is None:\n        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=\"Invalid or expired token\")\n\n    _set_media_cookie(request, response, token, remaining)\n    return MediaCookieResponse(success=True)\n\n\n@auth_router.get(\"/me\", response_model=UserDTO)\ndef get_current_user_info(\n    current_user: CurrentUser,\n) -> UserDTO:\n    \"\"\"Get current authenticated user's information.\n\n    Args:\n        current_user: The authenticated user's token data","sourceCodeStart":299,"sourceCodeEnd":335,"githubUrl":"https://github.com/invoke-ai/InvokeAI/blob/0b6a024f2ff6a86bfb953dcdb9cc504ef7397a06/invokeai/app/api/routers/auth.py#L299-L335","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Send a valid 'Authorization: Bearer <token>' header obtained from /auth/login","Re-login to get a fresh token, then retry the refresh call","Check any reverse proxy isn't stripping the Authorization header","Fix the client to keep the token before invoking this endpoint"],"exampleFix":"// before\nawait api.post('/auth/media-cookie'); // no auth header\n// after\nawait api.post('/auth/media-cookie', { headers: { Authorization: `Bearer ${token}` } });","handlingStrategy":"type-guard","validationCode":"token = get_stored_token()\nif not token:\n    token = relogin()  # obtain a fresh Bearer token before calling the endpoint\n\nheaders = {'Authorization': f'Bearer {token}'}","typeGuard":"def has_bearer_token(headers: dict) -> bool:\n    auth = headers.get('Authorization', '')\n    return auth.startswith('Bearer ') and len(auth) > len('Bearer ')","tryCatchPattern":"try:\n    resp = requests.post(f'{base}/auth/media-cookie', headers=headers)\n    resp.raise_for_status()\nexcept requests.HTTPError as e:\n    if e.response.status_code == 401:\n        relogin_and_retry()","preventionTips":["Always attach the Authorization header explicitly; don't rely on cookies for this endpoint","Check proxies don't strip Authorization headers","Re-login if the stored token is missing before calling refresh endpoints","Handle 401 centrally with a re-login flow"],"tags":["http-401","authentication","bearer-token"],"backgroundTag":"missing-bearer-token","analyzedSha":"0b6a024f2ff6a86bfb953dcdb9cc504ef7397a06","analyzedAt":"2026-08-29T04:46:49.967Z","schemaVersion":2},"datasetVersion":"2026-08-29T07:17:48.351Z"}