Skip to content

Authentication & Authorization

**Referenced Files in This Document** - [[doc.go]](file/bi-common/auth/doc.go) - [[jwt.go]](file/bi-common/auth/jwt.go) - [[rbac.go]](file/bi-common/auth/rbac.go) - [[middleware.go]](file/bi-common/auth/middleware.go) - [[context.go]](file/bi-common/auth/context.go) - [[blacklist.go]](file/bi-common/auth/blacklist.go) - [[cache.go]](file/bi-common/auth/cache.go) - [[claims.go]](file/bi-common/auth/claims.go) - [[client.go]](file/bi-common/auth/client.go) - [[common.proto]](file/bi-common/conf/common.proto) - [[setup.go]](file/bi-common/cache/redisx/setup.go) - [[client.go]](file/bi-common/cache/redisx/client.go) - [[auth_test.go]](file/bi-common/auth/auth-test.go)

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion
  10. Appendices

Introduction

This document describes the unified authentication and authorization system built around JWT tokens and Role-Based Access Control (RBAC). It covers token lifecycle (generation, validation, refresh), middleware integration patterns, user context management, permission checking, blacklist handling, and optional integration with external identity providers via gRPC clients. It also outlines configuration via YAML and proto, environment variable overrides, and operational guidance for production deployments.

Project Structure

The authentication and authorization logic resides under bi-common/auth, with supporting Redis utilities under bi-common/cache/redisx. Configuration is defined in common.proto and consumed by the auth package.

Diagram sources

Section sources

Core Components

  • JWT utilities: token pair generation, access/refresh token creation, parsing, expiration checks, and refresh threshold evaluation.
  • RBAC middleware: path-based permission enforcement, support for management vs client APIs, caching of permissions, and wildcard permission matching.
  • Middleware orchestration: composition of JWT auth and RBAC into a cohesive pipeline with configurable whitelist and provider interfaces.
  • User context and metadata: propagation of user info across Kratos metadata and HTTP headers for downstream services.
  • Token blacklist: in-memory and Redis-backed implementations for logout and forced invalidation.
  • Permission cache: Redis-backed caching of user permissions with TTL.
  • gRPC client: client stubs for verifying tokens, fetching permissions, checking permissions, refreshing tokens, and invalidating tokens.
  • Configuration: proto-defined auth config with environment variable overrides.

Section sources

Architecture Overview

The system integrates JWT-based authentication with RBAC middleware and optional external identity provider integration. It supports:

  • Simple JWT auth (no RBAC)
  • JWT + RBAC for client APIs (without -m)
  • JWT + RBAC for management APIs (with -m) via bi-sys RPC
  • Cross-service propagation of user metadata
  • Token blacklist and Redis-backed caches

Diagram sources

Detailed Component Analysis

JWT Token Generation and Validation

  • Token pair generation produces an access token and a refresh token with separate expirations.
  • Access tokens carry standard claims and user attributes; refresh tokens are issued for extended sessions.
  • Parsing validates signature, issuer, and time-bound claims, returning structured errors for malformed/expired/not-yet-valid tokens.
  • Refresh threshold determines whether a token should be refreshed before use.

Diagram sources

Section sources

RBAC Implementation and Permission Checking

  • RBAC distinguishes management APIs (paths containing -m) from client APIs.
  • Management APIs restrict access to system users (TenantID=0) and bypass permission checks for super admins.
  • Client APIs allow super or admin users to bypass permission checks; others require provider-backed permission retrieval with optional caching.
  • Default path-to-permission mapping supports CRUD-like semantics; a method-aware variant is available.
  • Wildcard matching supports module-level and action-level wildcards.

Diagram sources

Section sources

Middleware Integration Patterns

  • AuthMiddlewares composes JWTAuthMiddleware followed by RBACMiddleware when providers are configured.
  • SimpleAuthMiddleware provides lightweight JWT-only authentication for login and similar endpoints.
  • HeaderAuthMiddleware trusts pre-validated user info passed via headers (useful for gateway scenarios).

Diagram sources

Section sources

User Context Management and Metadata Propagation

  • User context stores user identity and roles; getters provide typed accessors.
  • Kratos metadata is populated for cross-service propagation; client metadata is appended for downstream gRPC calls.
  • HeaderAuthMiddleware reconstructs user info from headers for trust-on-gateway setups.

Diagram sources

Section sources

Token Blacklist Handling

  • TokenBlacklist interface supports adding, checking, and removing tokens.
  • MemoryBlacklist is for testing/single-instance deployments.
  • RedisTokenBlacklist persists blacklist entries with TTL derived from token expiration.

Diagram sources

Section sources

Multi-Tenant Authorization and Session Management

  • TenantID distinguishes system users (TenantID=0) from tenant users.
  • Management APIs enforce system-only access; client APIs enforce tenant-scoped permissions.
  • Sessions are stateless via JWT; refresh tokens enable long-lived sessions with controlled lifetimes.

Section sources

Token Refresh Mechanisms

  • Refresh tokens are generated alongside access tokens.
  • Refresh threshold triggers automatic refresh logic before use.
  • A dedicated gRPC client method supports server-side refresh and invalidation.

Section sources

Audit Logging and Observability

  • The system does not define explicit audit logging hooks in the referenced files. Services should integrate logging around authentication events (login, token refresh, permission denials) using the platform’s logging facilities.

[No sources needed since this section provides general guidance]

Security Best Practices

  • Prefer environment variable overrides for secrets and issuers.
  • Use short access tokens with refresh tokens for long sessions.
  • Enforce HTTPS and secure cookie policies where applicable.
  • Regularly rotate secrets and monitor token issuance.
  • Limit scope of permissions and leverage wildcard sparingly.

Section sources

Integration with External Identity Providers

  • The gRPC client exposes VerifyToken, GetUserPermissions, CheckPermission, RefreshToken, and InvalidateToken.
  • PermissionProvider and PermissionCache interfaces enable pluggable backends (local, bi-tenant, or bi-sys RPC).

Section sources

Dependency Analysis

The auth package depends on Kratos middleware and transport, JWT library, and optional Redis for caching and blacklist persistence. Configuration is driven by proto messages and environment variables.

Diagram sources

Section sources

Performance Considerations

  • Enable Redis-backed PermissionCache to reduce provider calls; tune TTL to balance freshness and latency.
  • Use RedisTokenBlacklist for distributed deployments to avoid memory-only blacklists.
  • Keep access tokens short-lived; rely on refresh tokens for extended sessions.
  • Avoid excessive wildcard permissions; prefer granular permissions for better performance and security.

[No sources needed since this section provides general guidance]

Troubleshooting Guide

Common issues and resolutions:

  • Unauthorized due to missing or malformed Authorization header.
  • Token expired or not valid yet; refresh or re-authenticate.
  • Forbidden due to insufficient permissions; verify provider configuration and cache.
  • Token invalidated by blacklist; ensure logout/invalidate flows update blacklist.

Operational checks:

  • Validate JWTConfig via environment variables and proto.
  • Confirm Redis connectivity and cache TTL.
  • Verify provider implementations and RPC endpoints.

Section sources

Conclusion

The authentication and authorization system provides a robust, extensible foundation for JWT-based identity and RBAC-driven permissions. It supports diverse deployment patterns—from simple JWT auth to complex multi-tenant environments with management and client API segregation—while offering pluggable providers, caching, and blacklist capabilities for production-grade reliability.

Appendices

Configuration Examples

  • YAML-based auth configuration with JWT settings and whitelist.
  • Environment variables override secrets and issuer.
  • Proto-defined Auth message for structured configuration.

Section sources