Skip to main content

authentication-authorization-system

table-of-contents

introduction

this document serves as the security documentation for the sparrow authentication and authorization system, focusing on the following topics:

  • jwt authentication mechanism: token generation, refresh, validation, and context injection
  • rbac permission control: casbin-based access control middleware
  • rsa public key verification: request signing, timestamps, nonces, and replay prevention
  • middleware system: jwt authentication, rsa client authentication, rbac authorization
  • permission models and security tokens: claim structures, roles, and scopes
  • best practices: password security, session management, permission design principles
  • third-party integrations: multi-factor authentication, security audit logs
  • security hardening: vulnerability protection, penetration testing recommendations, compliance requirements

project-structure

key directories and files related to authentication and authorization are as follows:

  • authentication core: token generation, claims, principals, rsa interfaces and implementations
  • http middleware: jwt authentication, rsa client authentication, rbac authorization
  • bootstrap and assembly: authorization container, middleware registration
  • configuration: casbin model and policy paths
  • session entity: session lifecycle and expiration management
  • token-structure-and-generation
    • token: encapsulates access token, refresh token, scope, and expiration duration
    • tokengenerator: unified generation and refresh of jwt tokens, supports custom expiration strategies
    • userclaims: extended registered claims, containing user identifier and role list
    • principal: carries current user identity (username, userid, roles) in request context
  • rsa-client-authentication
    • rsaauthconfig: configurable request headers, time window, storage and cache interfaces
    • noncestore/signaturecache/publickeyprovider: abstract interfaces, in-memory implementation for demonstration
    • rsaclientauthmiddleware: rsa-pss based signature verification, timestamp validation, replay prevention
  • rbac-authorization
    • rbacmiddleware: casbin-based policy enforcement, authorization by resource and action
    • casbinconfig: model and policy file path configuration
  • bootstrap-and-assembly
    • authorization: centralized registration and retrieval of middleware, holds tokengenerator

the following diagram shows the call chain and responsibility division of authentication and authorization at the http layer.

jwt-authentication-mechanism

  • token-generation-and-refresh
    • generate access token and refresh token, set different expiration times respectively
    • use hs256 to sign claims, secret injected at application startup
    • refresh flow: parse refresh token, validate validity, update issuance time, reissue new token pair
  • token-validation-and-context-injection
    • middleware parses bearer token from authorization header
    • use userclaims to parse and validate signature, expiration, and effective time
    • after success, write principal to request context for subsequent handlers to use
  • authorization-model
    • casbin-based policy enforcement, resource is uri, action is http method
    • middleware retrieves username from context, executes e.enforce(username, obj, act)
  • configuration
    • provide model_path and policy_path through casbinconfig to load policies
  • security-validation-steps
    • read request headers: clientid, signature(base64), nonce, timestamp
    • validate timestamp: difference from server time not exceeding timewindow
    • replay prevention: check if nonce already exists, reject if exists
    • get public key: retrieve from publickeyprovider based on clientid
    • read request body and concatenate data: clientid + nonce + timestamp + body
    • decode signature and verify using rsa-pss(sha256)
    • cache signature result: improve performance, avoid repeated calculations
    • record nonce: write to noncestore, set expiration time
  • in-memory-implementation
    • memorynoncestore: map-based non-concurrent-safe storage, with periodic cleanup goroutine
    • memorypublickeyprovider: in-memory mapping of clientid to public key
    • memorysignaturecache: caches verification results, with expiration cleanup
  • middleware-registration-and-retrieval
    • authorization container responsible for collecting and naming middleware, facilitating on-demand enabling
  • middleware-combination-order
    • suggested order: rsa-client-authentication → jwt-authentication → rbac-authorization → business-handler
    • ensure identity and permission validation is completed before entering business logic
  • claims-and-principals
    • userclaims: contains registered claims and custom fields (userid, roles)
    • principal: carries current user identity information in context
  • token-structure
    • token: encapsulates access token, refresh token, scope, and expiration duration
  • session-management
    • session-entity: contains data and expiration time, provides expiration judgment and ttl update
  • generation-flow
    • construct userclaims, set issuer, subject, expiration, and issuance time
    • use hs256 and secret to sign and generate access token
    • refresh token uses longer validity period, other logic is consistent
  • validation-flow
    • middleware parses authorization header, validates signature method and key
    • uses jwt-go v5 error classification for fine-grained error handling
    • after success, injects principal into context
  • component-coupling
    • middleware depends on authentication core (claims, principal, error constants)
    • rsa middleware depends on rsa interface and in-memory implementation
    • rbac middleware depends on casbin configuration
    • bootstrap module centrally manages middleware and token generator
  • external-dependencies
    • jwt-go v5: jwt parsing and validation
    • gin: http middleware framework
    • casbin: rbac policy engine
    • standard-library: crypto, encoding, time, etc.
  • signature-cache
    • memorysignaturecache reduces repeated calculations by caching verification results, recommended for high-concurrency scenarios
  • nonce-cleanup
    • memorynoncestore and memorysignaturecache periodically clean expired items to avoid memory bloat
  • time-window
    • reasonably set timewindow to balance security and timeliness
  • concurrent-safety
    • current in-memory implementation is not locked, production environment recommended to replace with thread-safe storage implementation (such as redis)

[this-section-provides-general-performance-recommendations,-no-specific-file-sources-listed]

troubleshooting-guide

  • jwt-related
    • missing authorization header or format error: middleware directly returns 401
    • token format error, expired, or invalid signature: return corresponding prompts based on jwt-go v5 error types
    • test-coverage: includes invalid tokens, expired tokens, wrong signature methods, etc.
  • rsa-related
    • missing request headers, invalid timestamp, duplicate request, invalid signature, unauthorized client, failed to read request body
    • test-coverage: normal, missing headers, invalid clientid, invalid signature, expired timestamp, replay attack
  • rbac-related
    • unauthenticated (no username): returns 401
    • policy mismatch: returns 403

sparrow's authentication and authorization system takes clear layering and pluggable middleware as its core, combining jwt, rsa client authentication, and rbac authorization to form a complete and extensible security foundation. through reasonable token lifecycle, strict request validation, and configurable permission models, the system can meet most enterprise-level security requirements. it is recommended to introduce thread-safe storage implementations, comprehensive audit logs, and multi-factor authentication capabilities in production environments, and continuously conduct security assessments and penetration testing.

[this-section-is-summary-content,-no-specific-file-sources-listed]

appendix

best-practices-checklist

  • password-security
    • use strong hash algorithms with sufficient iteration counts; avoid storing passwords in plaintext
    • introduce salt and randomization; regularly rotate keys and certificates
  • session-management
    • session-entity provides expiration and ttl update capabilities, recommended to combine with refresh token strategy
    • strictly control session data minimization, avoid sensitive information persistence
  • permission-design-principles
    • least privilege and separation of duties; separation of resources and actions (rbac)
    • centralized policy management, version control for model and policy files
  • third-party-integrations
    • oauth2/openid-connect: access through independent gateway or adapter
    • multi-factor-authentication: sms/email verification codes, totp, hardware keys
  • security-audit-logs
    • record login/logout, token issuance/refresh, permission denial events
    • log desensitization and retention policies, support retrieval and alerting
  • vulnerability-protection-and-compliance
    • regularly conduct penetration testing and code audits
    • follow owasp-top-10,等级保护-2.0-or-iso-27001-standards
    • enforce-https,-csp,-cors-and-security-response-headers

[this-section-is-general-best-practices,-no-specific-file-sources-listed]