Tenant Authentication and Authorization
Table of Contents
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
- Appendices
Introduction
This document describes a tenant-aware authentication and authorization system built on JWT-based identity, Kratos middleware, and a unified RBAC model. It covers:
- Tenant-specific login and user context propagation
- Session management via access/refresh tokens and blacklist
- Tenant switching and cross-service metadata propagation
- Role-based access control (RBAC) within tenant contexts, including permission hierarchies and wildcard support
- User provisioning and menu initialization flows
- API surface for authentication endpoints and token management
- Security considerations including tenant isolation and audit-ready patterns
- Common scenarios and troubleshooting guidance
Project Structure
The authentication and authorization logic is primarily implemented in the shared library and exposed via protocol buffers across services:
- Shared auth primitives and middleware live under bi-common/auth
- Cross-service auth RPC contract is defined under bi-common/api/auth/v1
- Tenant and system management authentication endpoints are defined under bi-tenant/api/tenant/v1 and bi-sys/api/sys/v1 respectively
Diagram sources
- [rbac.go]
- [jwt.go]
- [context.go]
- [blacklist.go]
- [cache.go]
- [middleware.go]
- [auth.proto]
- [auth.proto (tenant)]
- [auth.proto (sys)]
Section sources
- [rbac.go]
- [jwt.go]
- [context.go]
- [claims.go]
- [blacklist.go]
- [cache.go]
- [middleware.go]
- [auth.proto]
- [auth.proto (tenant)]
- [auth.proto (sys)]
Core Components
- JWT utilities: token generation, parsing, expiration thresholds, and refresh decisions
- Auth middleware: JWT authentication and RBAC enforcement
- RBAC middleware: path-based permission checks, admin bypass, and caching
- Context and metadata: tenant/user info propagation across services
- Token blacklist: logout and forced invalidation
- Permission cache: Redis-backed caching of user permissions
- Cross-service auth RPC: VerifyToken, GetUserPermissions, CheckPermission, RefreshToken, InvalidateToken
Section sources
Architecture Overview
The system enforces tenant-aware authentication and RBAC across services:
- Clients call tenant or system authentication endpoints to obtain tokens
- Services attach JWTAuthMiddleware to enforce authentication and populate user context
- RBACMiddleware enforces permissions based on path patterns and cached permissions
- Cross-service calls propagate user context via Kratos metadata
- Token lifecycle is managed via refresh and blacklist mechanisms
Diagram sources
Detailed Component Analysis
JWT and Token Lifecycle
- Claims carry tenant/admin flags and role IDs; supports bi-sys and bi-tenant contexts
- Access/refresh token pair generation with configurable expirations and issuer
- Token parsing with explicit error mapping for malformed/expired/not-valid-yet
- Refresh threshold triggers proactive refresh logic
Diagram sources
Section sources
Authentication Middleware and Context Propagation
- JWTAuthMiddleware validates Authorization header, checks blacklist, parses claims, and injects UserInfo into context
- Sets Kratos metadata and client metadata for downstream propagation
- HeaderAuthMiddleware trusts pre-validated headers for downstream services
Diagram sources
Section sources
RBAC Middleware and Permission Model
- Path-based permission mapping with optional custom PathToPermFunc
- Supports wildcard permissions (module:resource:, module:)
- Admin/super admin bypass for tenant/system APIs
- Optional Redis cache for permissions
Diagram sources
Section sources
Cross-Service User Propagation
- Kratos metadata keys include user ID, tenant ID, username, roles, and admin flags
- Downstream services can trust headers or metadata to avoid re-authentication
- Supports x-md-global- prefix for client metadata propagation
Diagram sources
Section sources
Token Blacklist and Session Management
- Blacklist supports in-memory and Redis backends
- Used to invalidate tokens on logout or forced sign-out
- Redis blacklist stores token keys with TTL derived from token expiration
Diagram sources
Section sources
Permission Cache
- Redis-backed cache for user permissions with configurable TTL and key prefix
- Reduces repeated RPC calls to permission providers
Section sources
Cross-Service Auth RPC
- VerifyToken: validate token and return claims
- GetUserPermissions: fetch user permissions
- CheckPermission: check single permission
- RefreshToken: issue new tokens
- InvalidateToken: mark token invalid
Section sources
Tenant and System Authentication Endpoints
- Tenant AuthService endpoints: login, logout, refresh, info, menus, init, favorite
- System AuthService endpoints: login, logout, refresh, userinfo, menus
- Both use JWT and Kratos gateway annotations for HTTP mapping
Section sources
Dependency Analysis
- JWT depends on claims and configuration
- RBAC depends on permission providers and optional cache
- Context depends on Kratos metadata and transport
- Blacklist and cache depend on Redis client
- Middleware composes JWT and RBAC into a chain
Diagram sources
Section sources
Performance Considerations
- Enable RedisPermissionCache to reduce RPC calls to permission providers
- Tune RefreshThreshold to balance refresh frequency vs. token validity windows
- Use whitelisting for low-churn endpoints to avoid middleware overhead
- Prefer HeaderAuthMiddleware in downstream services when traffic is already gateway-validated
Troubleshooting Guide
Common issues and resolutions:
- Unauthorized due to missing/expired/invalid token
- Verify Authorization header format and token validity
- Check blacklist status if logout was performed
- Forbidden due to insufficient permissions
- Confirm required permission mapping for endpoint path
- Ensure wildcard permissions are configured (e.g., module:resource:*)
- Cross-service tenant leakage
- Validate Kratos metadata keys are set and propagated
- Ensure downstream services use HeaderAuthMiddleware or metadata extraction
- Permission cache staleness
- Clear Redis cache keys for affected users or adjust TTL
- Refresh threshold misconfiguration
- Adjust RefreshThreshold to prevent premature refresh failures
Section sources
Conclusion
The system provides a robust, tenant-aware authentication and authorization framework:
- Strong separation between tenant and system contexts
- Flexible RBAC with wildcard support and caching
- Secure token lifecycle with blacklist and refresh controls
- Cross-service propagation of tenant/user context
- Extensible RPC contract for permission verification and token management
Appendices
API Reference: Authentication Endpoints
- Tenant AuthService
- POST /api/v1/tenant/auth/login
- POST /api/v1/tenant/auth/logout
- POST /api/v1/tenant/auth/refresh
- GET /api/v1/tenant/auth/info
- GET /api/v1/tenant/auth/menus
- GET /api/v1/tenant/auth/init
- POST /api/v1/tenant/auth/favorite
- GET /api/v1/tenant/auth/favorite
- System AuthService
- POST /api/v1/auth/login
- POST /api/v1/auth/logout
- POST /api/v1/auth/refresh
- GET /api/v1/auth/userinfo
- GET /api/v1/auth/menus
Section sources
RBAC Permission Mapping Examples
- GET /api/v1/tenant/users → tenant:user:list
- GET /api/v1/tenant/users/{id} → tenant:user:get
- POST /api/v1/tenant/users → tenant:user:create
- PUT/PATCH /api/v1/tenant/users/{id} → tenant:user:update
- DELETE /api/v1/tenant/users/{id} → tenant:user:delete
Wildcard examples:
- tenant:*
- tenant:user:*
Section sources