Skip to content

Authentication and Security

**Referenced Files in This Document** - [[auth.go]](file/bi-api-jushuitan/common/sdkhelper/auth.go) - [[client.go]](file/bi-api-jushuitan/common/sdkhelper/client.go) - [[types.go]](file/bi-api-jushuitan/common/sdkhelper/types.go) - [[auth_test.go]](file/bi-api-jushuitan/common/sdkhelper/auth-test.go) - [[jushuitan.go]](file/bi-api-jushuitan/internal/data/client/jushuitan.go) - [[main.go]](file/bi-api-jushuitan/cmd/bi-api-jushuitan/main.go) - [[wire.go]](file/bi-api-jushuitan/cmd/bi-api-jushuitan/wire.go) - [[wire_gen.go]](file/bi-api-jushuitan/cmd/bi-api-jushuitan/wire-gen.go) - [[application-dev.yaml]](file/bi-api-jushuitan/configs/application-dev.yaml) - [[application-prod.yaml]](file/bi-api-jushuitan/configs/application-prod.yaml)

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 explains the authentication and security mechanisms for accessing the Jushuitan (Ju Shui Tan) Open Platform APIs within the bi-api-jushuitan module. It covers the OAuth2-like authorization flow, API key and secret management, signature-based request authentication, token refresh strategies, session management, credential rotation, rate limiting, IP whitelisting, and quota enforcement. It also provides secure client initialization examples, error handling guidance, and best practices aligned with enterprise security policies, including audit logging and monitoring for suspicious activities.

Project Structure

The authentication and security logic is primarily implemented in the common SDK helper package and wired into the application via dependency injection. The runtime configuration is loaded from Nacos, and the application initializes the Jushuitan SDK client with credentials and timeouts.

Diagram sources

Section sources

Core Components

  • OAuth2-like Authorization Client: Builds authorization URLs, exchanges authorization codes for tokens, retrieves initial tokens, and refreshes access tokens using refresh tokens.
  • Request Signing Client: Encodes requests with app_key, access_token, timestamp, charset, version, biz payload, and MD5 signature.
  • Error and Response Types: Standardized response envelope, success checks, and error codes including authentication, IP, signature, rate limit, and permission errors.
  • Secure Client Factory: Initializes the SDK client with app key, app secret, base URL, and timeout from configuration.

Key responsibilities:

  • Enforce signature algorithm correctness and parameter ordering.
  • Manage token lifecycle (initial acquisition, refresh, and expiration awareness).
  • Provide structured error handling for authentication failures and rate limiting.
  • Log requests and responses for auditability.

Section sources

Architecture Overview

The application loads configuration from Nacos, wires dependencies using Google Wire, and constructs a Jushuitan SDK client. Requests are signed and sent to the Jushuitan Open Platform endpoints. Responses are parsed and logged for auditing.

Diagram sources

Detailed Component Analysis

OAuth2-like Authorization Flow

The SDK supports:

  • Building an authorization URL with app_key, timestamp, charset, optional state, and signature.
  • Exchanging an authorization code for access and refresh tokens.
  • Retrieving initial tokens for self-developed merchant scenarios.
  • Refreshing access tokens using refresh_token before expiration.

Security controls:

  • Signature over sorted parameters prevents tampering.
  • Timestamp included to bound validity window.
  • Authorization URL and code have short-lived validity windows.

Operational notes:

  • Refresh access tokens proactively before expiry.
  • If refresh fails, re-initiate authorization flow.

Diagram sources

Section sources

Signature-Based Request Authentication

All business requests are signed using the appSecret and a deterministic parameter ordering:

  • Parameters include app_key, access_token, timestamp, charset, version, biz payload, and computed sign.
  • The signature is MD5 of the concatenated secret plus each sorted parameter key-value pair.

Diagram sources

Section sources

Token Management and Session Lifecycle

  • Access token is attached to each request.
  • Refresh token is used to obtain a new access token before expiry.
  • Expiration is provided in seconds; clients should schedule refresh accordingly.
  • CoID indicates the authorized ERP company ID.

Best practices:

  • Store refresh tokens securely and rotate credentials periodically.
  • Implement proactive refresh to avoid latency during peak hours.
  • Invalidate tokens on logout or credential changes.

Section sources

Secure Client Initialization

The SDK client is constructed with:

  • AppKey and AppSecret from configuration.
  • BaseURL pointing to the target environment (production or sandbox).
  • Timeout tailored for network reliability.
  • Optional logger for audit trails.

Diagram sources

Section sources

Error Handling and Audit Logging

  • Response envelope includes code and msg; success determined by code equals zero.
  • APIError wraps platform error codes for structured handling.
  • SDK logs requests and responses with latency and contextual metadata for auditability.

Common error categories:

  • Authentication errors (e.g., expired or invalid tokens).
  • IP whitelist violations.
  • Signature verification failures.
  • Rate limiting and quota exceeded.
  • Permission and parameter errors.

Section sources

Rate Limiting, IP Whitelisting, and Quota Management

  • Platform error codes indicate rate limit and too many requests conditions.
  • IP whitelist errors require adding caller IPs to the allowlist.
  • Implement client-side throttling and retries with exponential backoff.
  • Monitor error counters and latency distributions for anomaly detection.

Section sources

Dependency Analysis

The application depends on Nacos for configuration, Google Wire for dependency injection, and the Jushuitan SDK helper for authentication and request signing.

Diagram sources

Section sources

Performance Considerations

  • Tune HTTP client timeouts and connection pooling for predictable latency.
  • Batch requests where possible and implement client-side rate limiting.
  • Use proactive token refresh to avoid last-minute failures during spikes.
  • Monitor request latency and error rates to detect anomalies early.

Troubleshooting Guide

Common issues and resolutions:

  • Authentication errors: Verify appKey/appSecret, ensure signatures match parameter ordering, and refresh tokens before expiry.
  • IP whitelist errors: Add the caller’s IP to the allowlist.
  • Signature failures: Confirm charset, timestamp freshness, and absence of extra parameters.
  • Rate limit errors: Reduce request frequency, implement backoff, and monitor counters.
  • Network failures: Increase timeouts and add retry logic with jitter.

Audit and monitoring:

  • Enable SDK logging to capture request/response envelopes and latency.
  • Correlate logs with request IDs and timestamps.
  • Alert on elevated error rates, repeated signature failures, or unusual IP patterns.

Section sources

Conclusion

The bi-api-jushuitan module implements a robust, signature-based authentication mechanism for the Jushuitan Open Platform, complemented by OAuth2-like authorization and refresh flows. By enforcing strict signature validation, managing tokens proactively, and logging all interactions, the system meets enterprise-grade security and operability requirements. Operators should integrate IP whitelisting, rate limiting, and continuous monitoring to maintain a secure and reliable integration.

Appendices

Secure Client Initialization Examples

  • Initialize SDK client with appKey, appSecret, baseURL, and timeout.
  • Set access token after successful authorization.
  • Use structured logging for auditability.

Section sources

Security Best Practices

  • Rotate appSecret and refresh tokens regularly.
  • Store secrets in a secure vault and avoid embedding in code.
  • Validate signatures deterministically and reject malformed requests.
  • Enforce IP allowlisting and monitor unauthorized access attempts.
  • Implement circuit breakers and retries with exponential backoff under rate limits.