Security Architecture and Authentication-Authorization Strategies in Microservices

Security Architecture and Authentication-Authorization Strategies in Microservices

Topic Description
Security is a critical aspect in microservices architecture. Since the system is decomposed into multiple independently deployable services, traditional monolithic application security solutions (such as Session-based authentication) are no longer applicable. This topic will delve into how to design and implement a unified, scalable security architecture in a microservices environment, focusing on core strategies for Authentication and Authorization. It covers Single Sign-On (SSO), token mechanisms (e.g., JWT), the role of API Gateways, and secure inter-service communication.

Knowledge Explanation

1. Core Challenges of Microservices Security

  • Decentralization: Numerous and dynamically changing service instances make it impossible to maintain a complete user authentication state (e.g., Session) within every service.
  • Inter-Service Call Security: When Service A calls Service B, it must ensure the request is legitimate and originates from a trusted service, not a malicious attacker.
  • Unified Access Control: A centralized mechanism is needed to manage access permissions for all microservices, avoiding duplicate implementation of authorization logic in each service.
  • Credential Propagation: User identity information (credentials) must be transmitted securely and efficiently across multiple service invocation chains.

2. Core Components and Architecture
The security architecture for microservices typically consists of several key components that work together to address the above challenges.

  • Identity Provider (IdP):

    • Description: The system responsible for authenticating user identities. It is the source of authentication.
    • Responsibilities: Verifies user identity (e.g., username/password, SMS verification code) and issues a credential (usually a Token) proving their identity.
    • Common Implementations: Can be a self-developed system, integrate third-party services like Okta or Auth0, or utilize open-source software like Keycloak.
  • API Gateway:

    • Description: Acts as the single entry point for all external requests and is the first line of defense for security.
    • Security Responsibilities:
      1. Authentication Interception: Intercepts all external requests to check for valid credentials (e.g., JWT). If absent, redirects to a login page or directly returns a 401 error.
      2. Routing and Forwarding: For authenticated requests, forwards the token (or key information from it) to backend business microservices.
      3. Basic Protection: Can additionally implement security policies like rate limiting and anti-crawling.
  • Token - Typically using JWT (JSON Web Token):

    • Description: A compact, self-contained credential format. It is a key technology for solving decentralization and credential propagation problems.
    • Structure: Consists of three parts separated by dots: Header, Payload, Signature (e.g., xxxxx.yyyyy.zzzzz).
      • Header: Typically contains the token type (e.g., JWT) and the signing algorithm (e.g., HS256).
      • Payload: Contains claims, which are statements about the user (and other metadata). Examples include user ID, username, roles, token expiration time, etc.
      • Signature: A signature for the first two parts, used to verify that the message hasn't been tampered with during transmission and to verify the issuer's identity.
    • Key Features:
      • Self-Contained: The Payload contains basic user information, allowing backend services to parse the user identity without querying a database or centralized session storage, enabling statelessness.
      • Verifiable: Signed using a secret key (known only to the issuing IdP). Any service holding this key (or the corresponding public key) can verify the token's authenticity.
  • Security Configuration Center (Optional but Recommended):

    • Description: Centrally manages security configurations for all microservices, such as public keys for JWT signature verification, blacklists/whitelists, and permission rules.

3. A Complete Request Flow (Problem-Solving Process)
Let's connect the above components through an example where a user accesses their "Order History" page.

  • Step 1: User Login and Token Acquisition

    1. The user enters their username and password on the frontend (e.g., web browser or mobile app).
    2. The frontend sends the login request to the API Gateway.
    3. The API Gateway routes the login request to the Identity Provider (IdP) microservice.
    4. The IdP verifies if the username and password are correct.
    5. Upon successful verification, the IdP generates a JWT. The JWT's Payload might contain: { "userId": "123", "username": "alice", "roles": ["member"], "exp": 1734567890 }.
    6. The IdP signs this JWT using its own private key and then returns the JWT to the frontend.
    7. The frontend receives the JWT and typically stores it locally (e.g., in LocalStorage or a Cookie).
  • Step 2: Accessing Protected Resources with Token

    1. The user wants to view their order history. The frontend attaches the JWT obtained in the previous step to the request header (usually Authorization: Bearer <JWT-Token>). It then sends the request to the API Gateway, e.g., GET /order-service/orders.
    2. API Gateway intercepts this request:
      • Authentication: The gateway extracts the JWT from the request header. It verifies the JWT's signature using a pre-configured public key (from the IdP). If the signature is invalid or the token has expired, the gateway directly returns a 401 Unauthorized error.
      • (Optional) Basic Authorization: The gateway can parse the roles claim in the JWT to check if the user's role has basic permission to access the /order-service/** path. If not, it returns 403 Forbidden. This step usually performs coarse-grained permission control.
  • Step 3: Inter-Service Calls and Token Propagation

    1. After successful gateway verification, the request (often with key information from the JWT, such as userId, extracted and placed into a new HTTP header like X-User-Id) is forwarded to the Order Service.
    2. Order Service receives the request:
      • It trusts that the API Gateway has completed authentication. It can directly use X-User-Id to identify the user.
      • Alternatively, for higher security, the Order Service can also re-verify the JWT (using the same public key) to ensure the token hasn't been tampered with after passing through the gateway.
    3. Order Service needs to call the User Service to obtain detailed user information.
    4. During inter-service calls, the Order Service needs to pass its own identity credentials (not the user's JWT) to the User Service. This is typically achieved through Mutual TLS (mTLS) or a Service Account Token, ensuring it's a legitimate inter-service call. This is inter-service security.
  • Step 4: Business Authorization

    1. The Order Service queries the order list from the database based on userId.
    2. Before returning the data, the Order Service must execute authorization logic: "User 123 can only view their own orders". This involves comparing the userId from the JWT (or the X-User-Id from the gateway) with the userId associated with the orders to be queried. This step is fine-grained data permission control.
  • Step 5: Returning Results
    The Order Service returns the filtered order list to the API Gateway, which then returns it to the frontend user.

Summary
The core of microservices security architecture is boundary security and tokenization. By concentrating complex authentication logic in the API Gateway and Identity Provider (IdP), business microservices are kept lightweight. JWT, as a stateless, self-contained token, is an ideal choice for implementing decentralized authentication and credential propagation. The entire process ensures that identity and permission information can be accurately and securely transmitted and verified from the end-user to the final service.