Skip to content

User Authentication and Authorization

**Referenced Files in This Document** - [[jwt.go]](file/bi-common/auth/jwt.go) - [[claims.go]](file/bi-common/auth/claims.go) - [[context.go]](file/bi-common/auth/context.go) - [[middleware.go]](file/bi-common/auth/middleware.go) - [[rbac.go]](file/bi-common/auth/rbac.go) - [[blacklist.go]](file/bi-common/auth/blacklist.go) - [[rbac.go]](file/bi-sys/internal/middleware/rbac.go) - [[rbac.go]](file/bi-tenant/internal/server/rbac.go) - [[auth.go]](file/bi-tenant/internal/biz/auth.go) - [[auth.go]](file/bi-tenant/internal/service/auth.go) - [[auth.go]](file/bi-sys/internal/biz/auth.go) - [[auth.go]](file/bi-sys/internal/service/auth.go) - [[auth.go]](file/bi-api-jushuitan/common/sdkhelper/auth.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 User Authentication and Authorization system across the platform. It covers the login flow, JWT token lifecycle, session handling, role-based access control (RBAC), tenant isolation, and cross-service propagation of authentication context. It also explains how to implement custom authentication guards, handle authentication errors, manage user sessions across browser tabs, and integrate with bi-sys and bi-tenant services for user management and tenant switching.

Project Structure

The authentication and authorization logic is primarily implemented in the bi-common library and integrated by services such as bi-sys (system management), bi-tenant (tenant management), and bi-api-* services. The key areas are:

  • JWT generation, parsing, and refresh thresholds
  • Claims model supporting both system and tenant contexts
  • Authentication middleware pipeline
  • RBAC permission checks and caching
  • Cross-service metadata propagation
  • Token blacklist support
  • Integration points with bi-sys and bi-tenant for permissions and user data

Diagram sources

Section sources

Core Components

  • JWT utilities: token pair generation, access/refresh token creation, parsing, expiration checks, and refresh threshold evaluation.
  • Claims model: unified JWT payload including user identity, tenant/admin flags, roles, and registered claims.
  • Authentication context: Kratos middleware to extract tokens, validate, populate user info into context, and propagate metadata across services.
  • RBAC middleware: path-based permission resolution, cache-aware permission retrieval, and enforcement for both client and management APIs.
  • Token blacklist: optional mechanism to invalidate tokens (logout, forced logout).
  • Cross-service propagation: metadata keys for user identity and roles passed via Kratos metadata and gRPC headers.

Section sources

Architecture Overview

The system enforces authentication and authorization at the gateway or per-service boundary using Kratos middleware. Tokens are validated centrally, user context is built, and permissions are checked against configured providers. For management APIs, bi-sys is used; for client APIs, bi-tenant provides permissions locally or via RPC.

Diagram sources

Detailed Component Analysis

JWT Token Management

  • Token pair generation: produces access and refresh tokens with distinct expirations and registered claims.
  • Access token validation: parses and verifies signature; distinguishes expired vs invalid tokens.
  • Refresh threshold: determines whether a token needs refreshing based on remaining validity.
  • Configuration: supports environment-driven defaults and proto-based overrides.

Diagram sources

Section sources

Authentication Context Provider and Protected Routes

  • Extracts Authorization header, strips bearer prefix, validates token, and populates UserInfo into Kratos context.
  • Propagates user metadata across services via Kratos metadata and gRPC client context.
  • Supports white-listed routes and optional blacklist checks.

Diagram sources

Section sources

Role-Based Access Control (RBAC)

  • Path-based permission mapping: converts URL patterns to permission identifiers (module:resource[:action]).
  • Management vs client distinction: management APIs require system-level access and bypass client permission checks.
  • Cache-first permission retrieval: reduces RPC/database load by caching user permissions.
  • Wildcard and prefix matching: supports flexible permission expressions.

Diagram sources

Section sources

Token Blacklist and Logout Handling

  • TokenBlacklist interface enables adding tokens to a blacklist with expiration.
  • MemoryBlacklist suitable for single-node deployments; Redis-backed implementation is available via configuration.
  • Middleware checks blacklist before allowing requests.

Diagram sources

Section sources

Tenant Isolation Patterns

  • Claims carry tenant_id and admin flags to enforce tenant boundaries.
  • Management APIs restrict access to system users (tenant_id=0).
  • Cross-service propagation ensures downstream services receive tenant-aware context.

Diagram sources

Section sources

Permission Checking Across Services

  • bi-tenant provides a PermissionProvider that aggregates role permissions for a user.
  • CombinedPermissionProvider selects bi-sys RPC for management APIs and local provider for client APIs.
  • bi-sys caches and serves permissions for super users.

Diagram sources

Section sources

Automatic Token Refresh Mechanisms

  • The JWT utility exposes a refresh threshold check to decide when to request a new access token.
  • Refresh tokens are generated separately and can be used to obtain a new access token pair.
  • Applications should proactively refresh tokens before the threshold to avoid interruptions.

Diagram sources

Section sources

Implementing Custom Authentication Guards

  • Use SimpleAuthMiddleware for pure authentication without RBAC checks.
  • Use AuthMiddlewares to compose JWT + RBAC with configurable providers and caches.
  • Define PermissionProvider implementations to supply permissions from local stores or RPC clients.

Diagram sources

Section sources

Handling Authentication Errors

  • Unauthorized: missing or invalid tokens, expired tokens, or blacklisted tokens.
  • Forbidden: insufficient permissions for the requested resource.
  • Internal errors: failures while fetching permissions.

Diagram sources

Section sources

Managing Sessions Across Browser Tabs

  • Use refresh tokens to obtain new access tokens when the current one is near expiry.
  • Store tokens securely (e.g., HttpOnly cookies or secure storage) and propagate Authorization headers consistently.
  • On tab switch, re-validate tokens and refresh as needed to maintain seamless UX.

[No sources needed since this section provides general guidance]

Integration with bi-sys and bi-tenant Services

  • bi-sys: Provides system-level RBAC checks and permission caching for super users and management APIs.
  • bi-tenant: Supplies tenant-scoped permissions and user role aggregation; integrates with bi-sys for management endpoints.

Diagram sources

Section sources

Dependency Analysis

  • bi-common/auth is the central dependency for all services requiring authentication and authorization.
  • bi-tenant depends on bi-sys for management API permission checks.
  • Cross-service metadata propagation relies on Kratos metadata keys defined in the auth context.

Diagram sources

Section sources

Performance Considerations

  • Enable permission caching to reduce repeated RPCs or database queries.
  • Use refresh thresholds to minimize token renewal overhead.
  • Keep white lists concise to avoid unnecessary middleware processing.
  • Prefer lightweight metadata propagation for cross-service calls.

[No sources needed since this section provides general guidance]

Troubleshooting Guide

  • Unauthorized errors:
    • Verify Authorization header format and presence.
    • Confirm token is not expired or blacklisted.
    • Ensure issuer and secret match across services.
  • Forbidden errors:
    • Check required permission mapping for the endpoint.
    • Confirm user has appropriate roles or is super/admin.
    • Validate cache consistency if using cached permissions.
  • Cross-service propagation:
    • Confirm Kratos metadata keys are set and forwarded.
    • Ensure downstream services use HeaderAuthMiddleware when relying on pre-authenticated gateways.

Section sources

Conclusion

The platform’s authentication and authorization system centers on robust JWT token management, a unified claims model, and a flexible RBAC middleware pipeline. By leveraging cross-service metadata propagation, configurable permission providers, and tenant-aware context, it supports secure, scalable multi-tenant operations. Integrations with bi-sys and bi-tenant enable both system-level and tenant-level controls, while token refresh and blacklist mechanisms improve resilience and security.

[No sources needed since this section summarizes without analyzing specific files]

Appendices

  • Example configuration patterns:
    • Default JWT configuration with environment overrides.
    • Auth middlewares composition with white lists, blacklists, and permission providers.
    • Permission provider implementations for tenant and system services.

Section sources