Detailed Explanation of Common Authentication Methods in Microservices

This article introduces several common authentication methods in microservices, helping you choose the appropriate authentication scheme when designing and implementing microservice systems.

Click to show the outline

In modern microservice architectures, security is a crucial aspect. As the number of microservices increases, ensuring secure communication between services becomes a challenge. This article will introduce several common authentication methods in microservices, helping you choose the appropriate authentication scheme when designing and implementing microservice systems.

Common Authentication Methods in Microservices

The table below lists several common authentication methods in microservices, comparing them from the perspectives of advantages, disadvantages, applicable scenarios, and real-world examples.

Authentication Method Advantages Disadvantages Deployment Location Applicable Scenarios Typical Uses Real-World Examples
JWT Self-contained token, reduces server load Larger token size, may increase bandwidth overhead API Gateway, Between Services Stateless communication between microservices User authentication and authorization User authentication in microservices (e.g., Auth0, Firebase)
OAuth 2.0 Widely supported, highly flexible Complex implementation, requires additional interactions API Gateway Third-party application authorization Third-party application access to user data GitHub OAuth for third-party applications accessing GitHub data and APIs
mTLS High security, prevents man-in-the-middle attacks Complex certificate management, significant performance overhead Between Services Communication requiring high security Secure communication between sensitive services Service communication in banking systems
Basic Authentication Simple and easy to implement Insecure, easily intercepted API Gateway, Between Services Simple API protection Simple internal services Basic authentication of Kubernetes API Server
API Key Authentication Simple and easy to use Low security, easily abused API Gateway, Between Services Scenarios with low security requirements Simple service access control Various public APIs, such as OpenAI API

Below we will introduce these common authentication methods in detail.

JWT Authentication

JWT (JSON Web Token) was first proposed by the IETF JSON Web Token (JWT) Working Group and was officially released as the RFC 7519 standard in 2015. The design goal of JWT is to provide a compact and self-contained way to securely transmit information between parties. Due to its ease of use and stateless nature, JWT quickly gained widespread adoption and became one of the standards for identity verification and information exchange, especially in microservices and modern web applications.

The following diagram shows the JWT authentication process.

image
JWT Authentication Process

JWT Authentication Process Explanation:

  1. User provides credentials
  2. Client requests access token
  3. Authentication server returns JWT token
  4. Client requests resource server with JWT token
  5. Resource server validates JWT

JWT Format and Example

A JWT (JSON Web Token) consists of three parts: Header, Payload, and Signature, each encoded with Base64 and concatenated with dots (.).

  1. Header: The header includes the type of token and the signing algorithm.

    {
      "alg": "HS256",
      "typ": "JWT"
    }
    
  2. Payload: The payload contains claims, which are assertions about the user or other data.

    {
      "sub": "1234567890",
      "name": "John Doe",
      "iat": 1516239022
    }
    
  3. Signature: The signature is generated by encoding the header and payload, and signing them with a secret using the algorithm specified in the header.

    HMACSHA256(
      base64UrlEncode(header) + "." +
      base64UrlEncode(payload),
      secret
    )
    

Below is an example of a JWT token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

OAuth 2.0

OAuth (Open Authorization) protocol was first proposed by Blaine Cook and Chris Messina in 2006. Initially, the goal was to provide an open authorization standard for Twitter. OAuth 1.0 was released in 2007, offering a standardized way for users to authorize third-party applications to access their resources. However, due to its complex signature mechanism and other security issues, it faced some limitations.

To overcome these shortcomings, the IETF (Internet Engineering Task Force) established the OAuth Working Group to develop a simpler, more flexible authorization protocol. In 2012, OAuth 2.0 was officially released (RFC 6749 and RFC 6750). OAuth 2.0 simplifies the authorization process, adding multiple authorization modes, such as authorization code mode, implicit mode, resource owner password credentials mode, and client credentials mode.

OAuth 2.0 quickly became an industry standard, widely used in various web services and applications such as Google, Facebook, GitHub, etc. Several extensions and complementary protocols (such as OpenID Connect) emerged based on it, further enhancing OAuth 2.0’s functionality and security.

The development and expansion of OAuth 2.0 have made it a cornerstone of modern internet authentication and authorization, providing a flexible and secure solution to meet the evolving needs of web applications.

The following diagram shows the OAuth 2.0 authentication process.

image
OAuth 2.0 Authentication Process

OAuth 2.0 Authentication Process Explanation:

  1. User requests access to resource
  2. Client requests authentication
  3. User logs in and authorizes
  4. Authorization server returns authorization code
  5. Client exchanges authorization code for access token
  6. Client requests resource server with access token

OAuth 2.0 Authorization Code

In the OAuth 2.0 authorization code mode, the authorization code is a short-term credential obtained by the client from the authorization server after user authorization, used to exchange for an access token. The authorization code is a temporary string that can be passed between the authorization server and the client to obtain a more secure access token.

OAuth 2.0 Extensions

OAuth 2.0 has developed many extensions to adapt to different scenarios. The table below lists some commonly used extensions, their main functions, and applicable scenarios.

Extension Name Main Function Applicable Scenarios
Authorization Code PKCE Extension Enhances the security of the authorization code mode, prevents authorization code interception attacks Public clients (e.g., mobile apps, single-page apps)
Dynamic Client Registration Protocol Allows clients to dynamically register and update client information Systems requiring high automation and flexibility
Token Introspection Allows resource servers to verify and obtain detailed information about access tokens Scenarios requiring token validity verification and detailed information
Token Revocation Provides a standard interface for token revocation Enhances system security and control
Device Authorization Grant Allows devices with limited input capabilities to complete authentication via other devices Devices with limited input capabilities (e.g., smart TVs, game consoles)
Mutual TLS Client Authentication Client authentication based on mutual TLS High-security application scenarios
Resource Indicators Allows clients to specify the resource server to access in the authorization request Support for multiple resource servers
Step-up Authentication Challenge Protocol Allows resource servers to request stronger authentication (e.g., multi-factor authentication) as needed Advanced authentication for high-risk operations

OAuth 2.0 Authorization Process (Using GitHub as an Example)

GitHub uses OAuth 2.

0 to authorize third-party applications to access users’ GitHub data. OAuth 2.0 tokens on GitHub are called “access tokens” and are used for authentication and authorization to access GitHub APIs. It provides a secure, standardized way for third-party applications to access GitHub resources with user authorization. By using access tokens, applications can perform various operations on behalf of users, such as reading user information, accessing repositories, creating gists, etc. This process ensures user security and privacy while simplifying the authentication and authorization process for applications.

The detailed process and examples of using GitHub OAuth 2.0 tokens are as follows:

  1. User Authorization: The user clicks the “Login with GitHub” button on the third-party application’s interface. The application redirects the user to GitHub’s authorization page.

  2. Obtain Authorization Code: The user logs in and agrees to authorize on the GitHub authorization page. GitHub redirects the user back to the application with an authorization code in the URL parameter.

    Example:

    https://yourapp.com/callback?code=AUTHORIZATION_CODE
    
  3. Exchange Access Token: The application server requests an access token from GitHub’s authorization server using the authorization code.

    Request Example:

    POST https://github.com/login/oauth/access_token
    Content-Type: application/json
    Accept: application/json
    
    {
      "client_id": "YOUR_CLIENT_ID",
      "client_secret": "YOUR_CLIENT_SECRET",
      "code": "AUTHORIZATION_CODE",
      "redirect_uri": "https://yourapp.com/callback"
    }
    
  4. GitHub Returns Access Token: GitHub validates the request and returns an access token.

    Response Example:

    {
      "access_token": "YOUR_ACCESS_TOKEN",
      "token_type": "bearer",
      "scope": "repo,gist"
    }
    
  5. Use Access Token to Access Resources: The application uses the obtained access token to access the GitHub API.

    Request Example:

    curl -H "Authorization: token YOUR_ACCESS_TOKEN" https://api.github.com/user
    

    Response Example:

    {
      "login": "github-user",
      "id": 1,
      "node_id": "MDQ6VXNlcjE=",
      "avatar_url": "https://github.com/images/avatar.jpg",
      "name": "Github User",
      "company": "GitHub",
      "blog": "https://example.com",
      "location": "Earth",
      "email": "[email protected]"
    }
    

Characteristics and Use of Access Tokens

  1. Scopes: The scope of an access token’s permissions is specified by the user during authorization and can include reading user profiles, accessing user repositories, managing gists, etc. For example, in the example above, the scope includes repo and gist.

  2. Validity and Refreshing: Access tokens can be long-term or have a specified time range until the user actively revokes them.

  3. Secure Transmission: Access tokens should be transmitted via HTTPS to ensure they are not intercepted.

mTLS

mTLS (Mutual TLS) is a technology that performs mutual authentication between the client and the server. It originated from the TLS (Transport Layer Security) protocol, the predecessor of which, SSL (Secure Sockets Layer), was developed by Netscape in 1995. With the increasing demand for internet security, TLS gradually evolved into a highly secure communication standard. mTLS further enhances security by requiring mutual authentication between both parties and is widely used in fields with high security requirements such as finance and healthcare.

The following diagram shows the mTLS authentication process.

image
mTLS Authentication Process

mTLS Authentication Process Explanation:

  1. Client and server mutually send certificates
  2. Both parties validate each other’s certificates
  3. Establish secure connection

For more information on TLS and mTLS, please refer to the blog post How Istio’s mTLS Traffic Encryption Works as Part of a Zero Trust Security Posture .

Basic Authentication

Basic Authentication is a simple authentication mechanism defined by the HTTP/1.0 specification (RFC 1945). It involves encoding the username and password with Base64 and appending them to the HTTP request header for authentication. Due to its simplicity and ease of use, Basic Authentication was widely adopted in early web applications. However, because of its inherent security issues (such as plain text transmission being easily intercepted), it is usually used with HTTPS or replaced by more secure authentication methods in modern applications.

The following diagram shows the Basic Authentication process.

image
Basic Authentication Process

Basic Authentication Process Explanation:

  1. User provides username and password
  2. Client requests resource server with username and password
  3. Resource server validates

Basic Authentication Example

Basic Authentication uses a Base64-encoded username and password for authentication. Below is an example of a Basic Authentication request using the curl command:

curl -u <username>:<password> https://api.example.com/data

If the username is admin and the password is password123, the request example is as follows:

curl -u admin:password123 https://api.example.com/data

API Key Authentication

API Key Authentication is a method of authenticating by including a pre-assigned unique key in the request. It became popular in the early 2000s with the rise of web APIs. Due to its simplicity and ease of management, API Key Authentication is widely used in various public and private APIs. Although it has lower security and is easily abused, it is still an effective means of access control in many scenarios, especially for applications that do not require high security protection.

The following diagram shows the API Key Authentication process.

image
API Key Authentication Process

API Key Authentication Process Explanation:

  1. Client requests resource server with API Key
  2. Resource server validates API Key

API Key Example

An API Key is a unique identifier passed in the request for client authentication. API Keys are typically passed through HTTP request headers or URL parameters.

Example of API Key in HTTP request header:

curl -H "Authorization: ApiKey YOUR_API_KEY" https://api.example.com/data

Example of API Key in URL parameter:

curl https://api.example.com/data?api_key=YOUR_API_KEY

An API Key is usually a string containing letters and numbers, for example:

1234567890abcdef1234567890abcdef

Summary

Choosing the right authentication method in a microservice architecture is crucial. Different authentication methods have their advantages and disadvantages in terms of security, complexity, and applicable scenarios. This article introduced five common authentication methods: JWT, OAuth 2.0, mTLS, Basic Authentication, and API Key Authentication, and provided their advantages, disadvantages, and applicable scenarios. Additionally, other common authentication methods such as SAML, LDAP, Kerberos, and OpenID Connect are also widely used in various internet application scenarios, especially in single sign-on and cross-domain authentication. I hope this information will help you choose the most suitable authentication scheme when designing and implementing microservice systems.

Last updated on Jun 19, 2024