User Authentication in Cognee
This document explains how user authentication functions in the Cognee backend in two distinct scenarios:
- When user authentication and authorization is handled by Cognee
- When Cognee is used as a third-party library and only uses bearer tokens generated with get_token.py to authenticate user requests
1. Authentication Handled by Cognee
Overview
When Cognee handles authentication, it uses FastAPI Users, a comprehensive authentication system for FastAPI. Cognee implements JWT (JSON Web Token) based authentication with bearer tokens, and supports user registration, login, password reset, and email verification flows.
Key Components
Authentication Backend
The authentication system is built around the AuthenticationBackend
class from FastAPI Users, with a custom JWT strategy:
- Bearer Transport: Used for transmitting tokens in the
Authorization
header - JWT Strategy: Customized to include user ID, tenant ID, and roles in the token payload
- Token Lifetime: Default is 1 hour (3600 seconds)
User Management
User management is handled through the UserManager
class, which provides:
- User registration
- Password management (reset, change)
- Email verification
- User retrieval and validation
- Custom post-registration hooks
Database Integration
Users are stored in a relational database, accessed through SQLAlchemy:
- User model includes email, password (hashed), tenant association, roles, and status flags
- User data is retrieved using async database sessions
Authentication Flow
Registration
- User submits registration data (email, password) to
/api/v1/auth/register
- The system validates the data and checks for existing users
- If valid, a new user is created with the provided details
- The password is securely hashed before storage
- Optional email verification can be enabled
Login
- User submits credentials to
/api/v1/auth/jwt/login
- The system validates the credentials against the stored user data
- If valid, a JWT token is generated with user information (user_id, tenant_id, roles)
- The token is returned to the client for use in subsequent requests
Authentication on API Requests
- Client includes the token in the
Authorization
header asBearer {token}
- The system extracts and validates the token on protected endpoints
- The user information is extracted from the token and made available to the endpoint
- Role-based access control can be implemented based on the roles in the token
Security Features
- Password hashing for secure storage
- Token expiration (1 hour by default)
- JWT signature validation to prevent tampering
- Protection against common attacks (CSRF, XSS)
- Role-based access control
Example Usage in API Endpoints
Protected endpoints use the get_authenticated_user
dependency to require authentication:
@router.post("/", response_model=None)
async def cognify(payload: CognifyPayloadDTO, user: User = Depends(get_authenticated_user)):
# Access to user.id, user.tenant_id, and user.roles
# Authenticated endpoint logic here
Frontend Integration
Cognee’s frontend stores the JWT token in localStorage and includes it in all API requests:
fetch('http://127.0.0.1:8000/api' + url, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
},
})
2. Cognee as a Third-Party Library with Bearer Tokens
Overview
When Cognee is used as a third-party library, authentication is handled externally, and Cognee only validates bearer tokens generated by the get_token.py
script. This approach is suitable for integrating Cognee into existing systems with their own authentication mechanisms.
Token Generation
The get_token.py
script provides a simple way to generate JWT tokens for authenticating with Cognee:
def create_jwt(user_id: str, tenant_id: str, roles: list[str]):
payload = {
"user_id": user_id,
"tenant_id": tenant_id,
"roles": roles,
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1), # 1 hour expiry
}
return jwt.encode(payload, SECRET_KEY, algorithm="HS256")
This function creates a signed JWT with:
- User ID
- Tenant ID
- Roles list
- Expiration time (1 hour from creation)
The token is signed with a secret key, which should be the same as the one used by the Cognee instance (FASTAPI_USERS_JWT_SECRET
environment variable).
Authentication Flow
- External System: Handles user authentication through its own mechanisms
- Token Generation: Uses
get_token.py
to create a bearer token with the user’s information - API Requests: Includes the token in the
Authorization
header - Cognee Validation: Validates the token and extracts user information
Implementation Steps
-
Import and use the token generation function:
from cognee.get_token import create_jwt # Generate a token for a user token = create_jwt( user_id="6763554c-91bd-432c-aba8-d42cd72ed659", tenant_id="tenant_456", roles=["admin"] )
-
Include the token in API requests:
headers = { "Authorization": f"Bearer {token}" } response = requests.get("http://{your-cognee-instance}/api/v1/settings", headers=headers)
Security Considerations
- Keep the secret key secure and consistent between token generation and Cognee
- Implement proper token expiration handling
- Ensure roles assigned in tokens align with the permissions needed
- Consider implementing token revocation if needed for security purposes
Custom Token Validation
The token validation in Cognee happens through the get_authenticated_user
function, which:
- Extracts the token from the Authorization header
- Verifies the token signature using the secret key
- Checks for token expiration
- Extracts and returns user information from the token payload
If token validation fails, the API returns appropriate HTTP error codes (401 for authentication issues).
Conclusion
Cognee provides flexible authentication options to suit different deployment scenarios:
-
Full Authentication Stack: When used as a standalone system, Cognee provides a complete authentication system with user management, registration, login, and token handling.
-
Token-Based Integration: When integrated into existing systems, Cognee can validate bearer tokens generated externally, allowing seamless integration with existing authentication mechanisms.
Both approaches use JWT tokens for secure authentication, with user, tenant, and role information included in the token payload to support authentication and authorization within Cognee’s functionality.