Skip to main content

Security Configuration

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. Appendix

Introduction

This document systematically organizes the "security configuration" capabilities of this project, focusing on the following aspects:

  • Casbin Permission Control: Model file path, policy file location, permission rule execution process
  • JWT Authentication: Secret key management, expiration time, signature algorithm, Claims structure and middleware validation
  • RBAC Permission Model: Role definition, permission assignment, resource access control
  • RSA Client Signature Authentication: Request header convention, time window, nonce anti-replay, signature verification
  • Security Best Practices: Password policy, session management, API protection and other recommendations

Project Structure

Key directories and files around security configuration are as follows:

  • Configuration Layer: Application configuration, Casbin configuration, configuration loading and validation
  • Authentication and Authorization: JWT token generation and validation, RBAC middleware, RSA client signature middleware
  • Context and Principal: UserClaims, Principal passing and usage
  • Bootstrap Layer: Authorization combines TokenGenerator and middleware registration

Core Components

  • Casbin Permission Control

    • Configuration Structure: Contains model file path and policy file path
    • Middleware: Extracts username from context, combines request URI and method to execute Enforce
  • JWT Authentication

    • Token Structure: Contains access token, refresh token, scope, expiration duration
    • Generator: Supports setting expiration time for access token and refresh token separately, uses HS256 signature
    • Middleware: Validates Bearer token, signature algorithm, expiration and not valid yet, signature validity; injects UserClaims and Principal
  • RBAC Permission Model

    • Roles and Permissions: UserClaims contains role array, Casbin middleware performs resource access control based on this
  • RSA Client Signature Authentication

    • Request Header Convention: Client ID, signature, nonce, timestamp
    • Anti-replay: NonceStore + time window
    • Signature Verification: SHA256 + RSA-PSS

Architecture Overview

The following diagram shows the interaction relationships and data flow between security related modules.

Detailed Component Analysis

Casbin Permission Control Configuration

Configuration Structure

  • Fields: Model file path, policy file path
  • Purpose: Initializes Casbin Enforcer's model and policy source

Middleware Behavior

  • Extracts username from context (requires preceding JWT middleware)
  • Extracts resource (URL) and action (HTTP method) from request
  • Calls Enforce to execute permission judgment, returns 403 or allows

JWT Authentication Configuration

Token Structure

  • Contains access token, refresh token, scope, expiration duration

Generator

  • Supports setting expiration time for access token and refresh token separately
  • Uses HS256 signature algorithm

Middleware

  • Validates Authorization header format (Bearer)
  • Uses UserClaims to parse and validate, distinguishes expiration, not valid yet, signature invalid and other scenarios
  • Injects Principal into context for subsequent use

RBAC Permission Model

Role Definition

  • Maintains role array in UserClaims

Permission Assignment

  • Defines authorization relationship between roles and resources/actions through Casbin policy file

Resource Access Control

  • Middleware executes Enforce based on username, resource, action
  • Returns 403 if unauthorized

RSA Client Signature Authentication Configuration

Request Header Convention

  • Client ID, Signature (Base64), Nonce, Timestamp

Anti-replay and Time Window

  • Uses NonceStore to record nonce and expiration time
  • Validates if timestamp is within allowed window

Signature Verification

  • Uses SHA256 + RSA-PSS to verify concatenated data

Cache Optimization

  • Uses SignatureCache to cache verification results, improves performance

Dependency Analysis

Configuration Loading

  • Reads multi-format configuration files through Load, automatic environment variable injection, validates required fields

Bootstrap Layer Authorization

  • Combines TokenGenerator and middleware list, supports named middleware registration and retrieval

Middleware Chain

  • JWT middleware → RSA client signature middleware (optional) → RBAC middleware → business handler

Performance Considerations

RSA Signature Cache

  • MemorySignatureCache provides memory-based signature verification result cache, reduces repeated computation

Nonce Cleanup

  • MemoryNonceStore and MemorySignatureCache both internally start periodic cleanup goroutine, avoids memory bloat

Recommendations

  • Recommend replacing with distributed cache (such as Redis) in production environment to support multi-instance sharing
  • Reasonably set TimeWindow and cache expiration time, balance security and performance

Troubleshooting Guide

  • 401 Unauthorized: Missing or malformed Authorization header
  • 401 Token Invalid: Malformed, expired, not valid yet, signature invalid
  • Recommendation: Confirm secret key consistency, algorithm match, time synchronization
  • 403 Forbidden: Username missing or policy does not grant this resource/action
  • Recommendation: Verify policy file and username, resource, action mapping
  • 401 Missing/Invalid Parameters: Request header missing or format error
  • 401 Timestamp Expired: Exceeds TimeWindow
  • 401 Duplicate Request: Nonce already exists
  • 401 Signature Verification Failed: Data concatenation or signature decoding exception
  • Recommendation: Ensure request body is completely read and reset, public key correct, time synchronized

Conclusion

This project provides complete authentication and authorization infrastructure:

  • Implements user identity authentication and token management through JWT
  • Implements fine-grained RBAC permission control through Casbin
  • Implements client signature authentication and anti-replay through RSA-PSS signature and time window, nonce mechanism
  • Configuration layer supports flexible loading and validation, bootstrap layer facilitates combining middleware and token generator

Recommend combining with distributed cache and key management service in production environment to further strengthen security and operability.

Appendix

Security Best Practices

  • Password Policy: Use strong hash algorithm and salt, regular rotation; avoid plaintext storage
  • Session Management: Short-lived access token + long-lived refresh token; enable HTTPS and SameSite Cookie
  • API Protection: Unified authentication middleware, rate limiting, input validation and principle of least privilege
  • Key Management: Key layering and rotation, hardware/cloud key management service, minimum exposure surface
  • Logging and Auditing: Record authentication events and exceptions, retain sufficient context but do not leak sensitive information