Authentication & Authorization API¶
Referenced Files in This Document
Table of Contents¶
Introduction¶
This document provides comprehensive API documentation for Nexo’s authentication and authorization system. It covers login with username/password validation, JWT token issuance and refresh, user registration, password reset, session management, role-based access control (RBAC), profile management endpoints, security headers, CORS policies, rate limiting strategies, client-side token handling, error responses, and security best practices.
Project Structure¶
The authentication and authorization features are implemented within the service layer:
-
Routes define HTTP endpoints for auth and user operations.
-
Shared schemas define request/response models.
-
Shared models define persistent entities.
-
Dependency injection wires security utilities and database sessions into routes.
-
Application configuration registers middleware and routers.
graph TB
subgraph "Service Layer"
A["routes/auth.py"]
B["routes/users.py"]
C["deps.py"]
D["app.py"]
E["main.py"]
end
subgraph "Shared"
F["schemas/auth.py"]
G["schemas/user.py"]
H["models/user.py"]
end
A --> F
A --> C
B --> G
B --> H
D --> A
D --> B
E --> D
Diagram sources
Section sources
Core Components¶
-
Authentication routes: login, logout, token refresh, password reset, and related flows.
-
User routes: registration, profile updates, password changes, account settings.
-
Schemas: validated request/response payloads for auth and user operations.
-
Models: user entity used by persistence and business logic.
-
Dependencies: shared security utilities (e.g., JWT helpers, password hashing) and DB session providers.
-
App wiring: middleware registration (CORS, security headers, rate limiting) and router mounting.
Key responsibilities:
-
Validate credentials and issue short-lived access tokens and longer-lived refresh tokens.
-
Enforce RBAC via dependency-injected current-user context and permission checks.
-
Provide secure password change/reset flows.
-
Maintain consistent error responses and status codes.
Section sources
Architecture Overview¶
High-level flow for authenticated requests:
-
Client sends request with an access token.
-
Security middleware validates the token and resolves the current user and roles.
-
Route handler executes business logic with RBAC checks.
-
Response includes appropriate security headers.
sequenceDiagram
participant Client as "Client"
participant Router as "Auth/User Routers"
participant Deps as "Security Deps"
participant Model as "User Model/DB"
participant App as "App Middleware"
Client->>Router : "POST /auth/login"
Router->>Model : "Validate credentials"
Model-->>Router : "User record"
Router->>Deps : "Issue access + refresh tokens"
Router-->>Client : "{access_token, refresh_token}"
Client->>Router : "GET /users/me"
Router->>Deps : "Verify access token"
Deps->>Model : "Load current user"
Model-->>Deps : "User object"
Router-->>Client : "Profile data"
Diagram sources
Detailed Component Analysis¶
Authentication Endpoints¶
-
Login: Validates username/password, returns access and refresh tokens.
-
Token Refresh: Accepts a valid refresh token to obtain a new access token.
-
Logout: Invalidates or expires the refresh token if server-side session is used.
-
Password Reset: Initiates reset flow (token/email) and completes reset.
Request/Response highlights:
-
Login payload includes username and password fields defined in the auth schema.
-
Responses include token types and expiration metadata.
-
Errors include invalid credentials and malformed requests.
flowchart TD
Start(["Login Request"]) --> Validate["Validate username/password"]
Validate --> Valid{"Valid?"}
Valid -- "No" --> Err["Return 401 Unauthorized"]
Valid -- "Yes" --> Issue["Issue access + refresh tokens"]
Issue --> Resp["Return tokens and expiry"]
Resp --> End(["Done"])
Diagram sources
Section sources
User Registration¶
-
Endpoint creates a new user with validated fields from the user schema.
-
Passwords are hashed before storage using the configured hashing strategy.
-
Returns created user representation without sensitive fields.
Error scenarios:
-
Duplicate username or email.
-
Validation failures on input fields.
Section sources
Password Reset Flow¶
-
Initiate reset: generates a time-bound reset token and stores it securely.
-
Complete reset: verifies token, enforces password policy, updates password hash.
Security considerations:
-
Tokens should be short-lived and single-use.
-
Rate limit reset attempts per user/IP.
Section sources
Profile Management¶
-
Get profile: returns current user’s non-sensitive profile data.
-
Update profile: allows updating safe fields; rejects sensitive changes unless authorized.
-
Change password: requires current password verification and enforces policy.
-
Account settings: toggles preferences where applicable.
Access control:
-
Users can update their own profiles.
-
Admins may manage other users’ profiles based on RBAC.
Section sources
Role-Based Access Control (RBAC)¶
-
Roles are attached to users and enforced via dependency-injected current user context.
-
Permission checks occur at route level or via decorators/middleware.
-
Common roles include admin and regular user; permissions map to actions like manage_users, update_profile, etc.
Implementation pattern:
-
Current user resolved from access token.
-
Optional role/permission guards validate access before route execution.
classDiagram
class User {
+id
+username
+email
+roles
+is_active
}
class AuthDeps {
+get_current_user(token)
+require_role(role)
+require_permission(permission)
}
class AuthRoutes {
+login()
+refresh()
+reset_password()
}
class UserRoutes {
+register()
+get_profile()
+update_profile()
+change_password()
}
AuthRoutes --> AuthDeps : "uses"
UserRoutes --> AuthDeps : "uses"
AuthDeps --> User : "loads"
Diagram sources
Section sources
Session Management¶
-
Stateless JWT access tokens carry minimal claims (user id, roles).
-
Refresh tokens may be stored server-side for revocation and rotation.
-
Logout invalidates refresh tokens when applicable.
Best practices:
-
Short access token lifetimes.
-
Secure, HttpOnly cookies for refresh tokens when browser-based.
-
Rotation on refresh to mitigate token theft.
Section sources
Security Headers, CORS, and Rate Limiting¶
-
Security headers: configure standard response headers (e.g., content-type options, strict transport security, frame options, XSS protection).
-
CORS: whitelist allowed origins, methods, and headers; restrict credentials usage.
-
Rate limiting: apply per-endpoint or global limits to protect login, refresh, and password reset.
Configuration points:
-
App initialization registers middleware and sets defaults.
-
Environment variables control allowed origins and limits.
Section sources
Dependency Analysis¶
Authentication and user routes depend on shared schemas and models, and use dependency injection for security and DB access. The app wires routers and middleware.
graph LR
Auth["routes/auth.py"] --> SchemaAuth["schemas/auth.py"]
Users["routes/users.py"] --> SchemaUser["schemas/user.py"]
Users --> ModelUser["models/user.py"]
Auth --> Deps["deps.py"]
Users --> Deps
App["app.py"] --> Auth
App --> Users
Main["main.py"] --> App
Diagram sources
Section sources
Performance Considerations¶
-
Keep access tokens small; avoid storing large claims.
-
Use efficient hashing algorithms with appropriate cost factors for passwords.
-
Cache frequently accessed user attributes where safe.
-
Apply rate limiting to reduce brute-force risk and protect resources.
-
Prefer stateless access tokens; store only necessary server-side state for refresh tokens.
[No sources needed since this section provides general guidance]
Troubleshooting Guide¶
Common issues and resolutions:
-
Invalid credentials: verify username/password and ensure account is active.
-
Expired access token: refresh using refresh token endpoint; handle 401 responses gracefully.
-
Invalid or revoked refresh token: prompt re-login; clear local tokens.
-
CORS errors: confirm origin is whitelisted and credentials mode matches server policy.
-
Rate limit exceeded: back off and retry after delay; implement exponential backoff.
Operational tips:
-
Log failed login attempts with sanitized details.
-
Monitor token refresh success/failure ratios.
-
Audit RBAC denials for potential misuse.
Section sources
Conclusion¶
Nexo’s authentication and authorization system combines JWT-based stateless access with optional server-side refresh token management, RBAC enforcement, and robust security configurations. By following the documented flows, error handling patterns, and best practices, clients can implement secure and resilient integrations.
[No sources needed since this section summarizes without analyzing specific files]
Appendices¶
Example Authentication Flows¶
-
Login: send username/password; receive access and refresh tokens; store securely.
-
Protected call: include access token in Authorization header; handle 401 by refreshing.
-
Refresh: present refresh token; receive new access token; rotate refresh token if supported.
-
Logout: invalidate refresh token if applicable; clear local tokens.
[No sources needed since this section provides conceptual examples]
Error Responses¶
-
400 Bad Request: malformed input or validation failure.
-
401 Unauthorized: invalid or missing credentials/token.
-
403 Forbidden: insufficient permissions or role mismatch.
-
404 Not Found: resource not found.
-
409 Conflict: duplicate username/email.
-
429 Too Many Requests: rate limit exceeded.
-
500 Internal Server Error: unexpected server error.
[No sources needed since this section provides general guidance]
Security Best Practices¶
-
Hash passwords with a strong algorithm and appropriate work factor.
-
Use HTTPS everywhere; enforce HSTS.
-
Set secure cookie flags for refresh tokens (HttpOnly, Secure, SameSite).
-
Minimize token lifetime and scope; rotate refresh tokens.
-
Validate and sanitize all inputs; reject unsafe values.
-
Implement rate limiting and account lockout thresholds.
-
Avoid logging secrets or tokens.
[No sources needed since this section provides general guidance]