Dosu LogoDosu Logo
Ask
Join our Discord
ragflowPublic
InfiniFlow
Documentsragflow
Authentication
Authentication
Type
Topic
Status
Published
Created
Jul 20, 2026
Updated
Jul 20, 2026

Authentication#

RAGFlow's authentication system is implemented in api/apps/__init__.py and supports four credential methods with a priority-based fallback chain. All protected routes use the @login_required decorator, which calls _load_user() on every request.


Auth Types and Constants#

Three auth-type string constants are defined at module level :

ConstantValueDefault?
AUTH_JWT"JWT"✅
AUTH_API"API"✅
AUTH_BETA"BETA"❌ (opt-in only)

DEFAULT_AUTH_TYPES = (AUTH_JWT, AUTH_API). Routes that need beta-token support must pass auth_types=[AUTH_BETA] explicitly to @login_required.


Resolution Order in _load_user()#

_load_user() tries credentials in this fixed sequence :

  1. Cache hit — if g.user is already populated and the auth type matches, return immediately.
  2. No Authorization header → fall through to session cookie (only if AUTH_JWT is in the allowed set).
  3. Beta token (if AUTH_BETA in allowed set) — looks up APIToken.query(beta=auth_token). Sets g.auth_type = "BETA".
  4. JWT (if AUTH_JWT in allowed set) — decodes the bearer token using itsdangerous.URLSafeTimedSerializer with settings.get_secret_key(), then queries UserService by access_token. Sets g.auth_type = "JWT".
  5. API key (if AUTH_API in allowed set) — looks up APIToken.query(token=auth_token) as a plain API token. Sets g.auth_type = "API".

The resolved auth type is written to g.auth_type; route handlers can inspect this if needed.

Session Cookie Fallback#

_load_user_from_session() is called only when the Authorization header is absent and AUTH_JWT is permitted. It reads _user_id from the Quart session (Redis-backed) and validates the associated access_token — rejecting empty values, values shorter than 32 chars, or values prefixed INVALID_. This path exists to support OAuth/OIDC redirect flows where the frontend may clear its stored bearer token after a 401.


Token Lifecycle#

EventEffect on access_token
Login (user_api.py)Set to a fresh UUID via get_uuid()
Logout / password change (user_api.py)Set to "INVALID_<hex>"

The INVALID_ prefix is checked in both _load_user_from_session() and UserService.query() to prevent revoked tokens from authenticating.

The JWT signing secret is a 64-char hex string lazily created and stored in Redis, shared across all server instances .

The APIToken model stores both plain API keys (token field) and beta tokens (beta field), scoped by tenant_id. The composite primary key is (tenant_id, token).


Error Handling#

Failed auth raises QuartAuthUnauthorized for most routes, returning HTTP 401 . The one exception: routes restricted to AUTH_BETA only return a JSON DATA_ERROR response instead of a 401 , matching the external API convention.

Error codes live in common/constants.py:

  • UNAUTHORIZED = 401
  • AUTHENTICATION_ERROR = 109
  • PERMISSION_ERROR = 108

Ownership-Based Authorization on Chat Endpoints#

Authentication (who you are) is separate from authorization (what you own). Chat and session endpoints enforce a second ownership check via _ensure_owned_chat(chat_id), which queries DialogService filtering by both tenant_id=current_user.id and id=chat_id. Any mutation route — PUT, PATCH, DELETE on /chats/<chat_id> and all /chats/<chat_id>/sessions/* routes — calls this guard before proceeding . A failed ownership check returns RetCode.AUTHENTICATION_ERROR (109), not 401.

The GET /chats/<chat_id> endpoint uses a broader check: it allows any tenant the user belongs to, not just their own — querying UserTenantService first .


Key Files#

FileRole
api/apps/__init__.py_load_user(), login_required, login_user(), logout_user()
api/apps/restful_apis/chat_api.pyChat/session ownership enforcement, _ensure_owned_chat()
api/apps/restful_apis/user_api.pyLogin/logout routes, access_token lifecycle
api/db/db_models.pyAPIToken model
common/settings.pyget_secret_key() — JWT signing secret
common/constants.pyRetCode enum
Documents
Agent Import and DSL Compatibility
Agent Prompt Processing
Agent Retrieval
API Authorization
API Error Codes
Ascend Inference Pipeline
Authentication
Azure OpenAI Integration
Canvas Architecture
Chat Assistant Configuration
Chat Completion API
Chrome for Testing ARM64 Support
Chunk Metadata Extraction
Chunker Pipeline
Compilation Template Management
Component Variable Propagation
Connection and Resource Management
Connector Architecture
Connector Document Sync
Conversation Session Management
What is the complete API flow for building a frontend UI with RAGFlow, covering dialogs, conversations, message history, streaming responses, and deletion?
Database Migrations
Dataflow Pipeline Execution
Dataset Access Control
Dataset Configuration UI
Dataset Parsing Mode
DeepDoc Model Distribution
DeepDoc Model Path Resolution
DeepDoc Module
Dify External Knowledge Integration
Docker Build Configuration
Document Parsing Pipeline
Elasticsearch Index Management
Embedding Pipeline
Embedding Vector Validation
Encrypted Storage
Figure Description Language Propagation
Frontend Build and Deployment
GPU and Accelerator Support
Hybrid Search and Retrieval
Infinity Database Stability
Internal Compilation Artifact Indexing
Keyword Extraction
Knowledge Compilation Pipeline
Knowledge Graph
Knowledge Graph Retrieval
Knowledge Graph Visualization
Layout Element Overlap Detection
LLM Configuration and Selection
LLM Driver Integration
LLM Provider Integration
MCP Server Integration
Media Context Configuration
Metadata Filtering
MinerU Configuration and Provider Resolution
MinerU PDF Parsing
Model Provider Architecture
Model Selection UI
Model Thinking and Reasoning
Multi-Architecture Docker Support
Multi-Backend Object Storage
Multi-Page Table and Element Handling
Multilingual Search Tokenization
Native Library Build and Linking
OCR Backend and Model Loading
Parser Configuration
Parser Output Lifecycle
Parser-Chunk Contract
PDF Chunk Position Rendering
Picture Chunker Media Processing
Pipeline Canvas Architecture
Provider Configuration Persistence
Provider Model Discovery
Python Dependency Management
RAGFlow Python SDK
Redis Cache Architecture
Retrieval API
Retrieval Pipeline
SSRF Protection
Table Column Field Normalization
Table Structure Parsing
Task Cancellation
Tenant Model Resolution
Text2SQL
TSR Coordinate System Alignment