Authentication and Authorization Service
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 the authentication and authorization service within bi-sys. It covers JWT token generation and validation, user login/logout flows, password hashing and verification, RBAC implementation, middleware integration, authentication API endpoints, security middleware configuration, token blacklisting, session management, and integration with other system services. It also includes examples of authentication flows, error handling, security best practices, token expiration policies, and audit logging for authentication events.
Project Structure
The authentication and authorization functionality spans two primary areas:
- bi-common/auth: reusable authentication primitives (JWT, RBAC, middleware, token blacklist, permission cache)
- bi-sys: concrete implementation of authentication APIs, use cases, repositories, and HTTP/gRPC bindings
Diagram sources
- [jwt.go]
- [claims.go]
- [blacklist.go]
- [cache.go]
- [middleware.go]
- [context.go]
- [rbac.go]
- [client.go]
- [auth_http.pb.go]
- [auth_grpc.pb.go]
- [auth.go]
- [user.go]
- [user.go]
Section sources
- [jwt.go]
- [claims.go]
- [blacklist.go]
- [cache.go]
- [middleware.go]
- [context.go]
- [rbac.go]
- [client.go]
- [auth_http.pb.go]
- [auth_grpc.pb.go]
- [auth.go]
- [user.go]
- [user.go]
Core Components
- JWT utilities: token pair generation (access + refresh), parsing, expiration checks, and refresh threshold logic
- Claims and configuration: standardized JWT payload with user identity, roles, and flags; configurable issuer, secrets, and expirations
- Token blacklist: in-memory and Redis-backed implementations for logout and forced sign-out
- Permission cache: Redis-backed caching of user permissions to reduce repeated RPC calls
- Authentication middleware: JWT parsing and user extraction, plus optional RBAC enforcement
- RBAC middleware: path-based permission mapping, support for management vs client APIs, caching, and wildcard permissions
- Auth client/provider: gRPC client for verifying tokens, fetching permissions, checking permissions, refreshing tokens, and invalidating tokens
- HTTP/gRPC bindings: endpoints for login, logout, refresh, user info, and menus
- Use cases and repositories: login/password verification, role resolution, token pair generation, logout logging, refresh flow, and user persistence
Section sources
- [jwt.go]
- [claims.go]
- [blacklist.go]
- [cache.go]
- [middleware.go]
- [context.go]
- [rbac.go]
- [client.go]
- [auth_http.pb.go]
- [auth_grpc.pb.go]
- [auth.go]
- [user.go]
Architecture Overview
The authentication service integrates HTTP and gRPC transports with middleware-driven JWT parsing and RBAC enforcement. Tokens carry user identity and roles, enabling downstream services to enforce access control consistently.
Diagram sources
Section sources
Detailed Component Analysis
JWT Token Generation and Validation
- Access and refresh token generation with HS256 signing
- Registered claims include issuer, subject, issued-at, not-before, and expiration
- Token pair includes access token TTL and bearer type
- Parsing validates signature and time-bound claims, returning structured errors
- Refresh threshold determines early refresh triggers
Diagram sources
Section sources
Password Hashing and Verification
- Password hashing uses bcrypt during user creation and password reset
- Login verifies password against stored hash using bcrypt comparison
- Errors are mapped to domain-specific errors and logged with context
Diagram sources
Section sources
RBAC Implementation and Middleware Integration
- RBAC middleware enforces permissions based on request path and method
- Supports management API differentiation via path patterns (e.g., containing “-m”)
- Super admin and tenant admin bypass permission checks
- Permission cache reduces repeated RPC calls to permission providers
- Wildcard permissions supported (module:, module:resource:, etc.)
Diagram sources
Section sources
Authentication API Endpoints
- HTTP endpoints:
- 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
- gRPC service:
- Login, Logout, RefreshToken, GetUserInfo, GetUserMenus
Diagram sources
Section sources
Security Middleware Configuration and Token Blacklisting
- JWTAuthMiddleware parses Authorization header, validates token, and injects user info into context and metadata
- Optional TokenBlacklist checks token against blacklist before allowing requests
- MemoryBlacklist for single-node testing; Redis-backed blacklist for distributed environments
- Cross-service propagation via metadata keys (x-user-id, x-tenant-id, x-username, x-is-super, x-is-admin, x-role-ids)
Diagram sources
Section sources
Session Management and Token Expiration Policies
- Access token expiration configured via JWTConfig; default 2 hours
- Refresh token expiration configured separately; default 7 days
- Refresh threshold determines when to trigger early refresh; default 30 minutes
- Logout does not currently invalidate tokens in storage; future enhancement can integrate Redis blacklist
Section sources
Audit Logging for Authentication Events
- Login attempts recorded with user agent parsing, IP, browser, OS, status, and message
- Logout recorded similarly
- Logs persisted via log repository abstraction
Section sources
Dependency Analysis
- bi-common/auth depends on:
- golang-jwt for token signing and parsing
- Redis client for token blacklist and permission cache
- Kratos middleware and transport for HTTP/gRPC integration
- bi-sys depends on:
- bi-common/auth for JWT, RBAC, and middleware
- bcrypt for password hashing
- Repositories for user and role data access
Diagram sources
Section sources
Performance Considerations
- Use Redis-backed permission cache to minimize RPC calls for permission checks
- Enable Redis blacklist for logout and forced sign-out to avoid unnecessary token parsing
- Keep refresh threshold reasonable to balance token lifetime and refresh frequency
- Cache frequently accessed user permissions per user ID with appropriate TTL
[No sources needed since this section provides general guidance]
Troubleshooting Guide
Common issues and resolutions:
- Unauthorized due to missing or invalid Authorization header
- Ensure Bearer token is included and formatted correctly
- Token expired or not valid yet
- Trigger refresh flow using refresh token endpoint
- Token blacklisted
- Confirm logout flow updates blacklist; verify Redis connectivity
- Insufficient permissions
- Verify user roles and permissions; check RBAC path-to-permission mapping
- Internal errors during password hashing or user operations
- Review bcrypt hashing and repository operations; check logs
Section sources
Conclusion
The authentication and authorization service provides a robust, modular foundation for secure access control across bi-sys. It leverages JWT for stateless identity, bcrypt for secure password handling, and RBAC for fine-grained permissions. Middleware integration ensures consistent enforcement across HTTP and gRPC boundaries, while Redis-backed caches and blacklists improve scalability and operational control.
[No sources needed since this section summarizes without analyzing specific files]
Appendices
API Endpoint Reference
- 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
Security Best Practices
- Store JWT_SECRET and other secrets in environment variables
- Enforce HTTPS/TLS in production
- Use short access tokens with frequent refresh
- Implement token blacklist for logout and compromised sessions
- Regularly rotate secrets and monitor token issuance
- Log and alert on suspicious login attempts
[No sources needed since this section provides general guidance]