Patterns
API Token Handler

API Token Handler

Problem

Unifying all your APIs and Services into a single API using the API Single Integration Architecture (opens in a new tab) and the Backend for Frontend Pattern is powerful. However, it brings about its own set of challenges, particularly in the realm of authentication & authorization.

In the context of a unified API, a key question arises: How do you authenticate users not just against your unified API, but also against the underlying services?

Solution

The Token Handler Pattern is an effective solution to these challenges. It is a technique that fits within the broader API Single Integration Architecture (opens in a new tab).

In the Token Handler Pattern, our BFF API Gateway functions as a secure token handler, meaning it facilitates the process of securely acquiring, storing, and renewing tokens for third-party services on behalf of the user.

Here are the key steps:

  1. User Authentication: The user authenticates against the API Gateway.

  2. Resource Access Request: The user attempts to access a resource from a third-party service.

  3. Authentication Check: The API Gateway checks if the user is authenticated against the third-party service.

  4. Authentication Redirect: If the user is not authenticated, the API Gateway redirects the user to the third-party service to start the authentication process.

  5. User Authentication with Third Party: The user authenticates against the third-party service.

  6. Redirection to API Gateway: The third-party service redirects the user back to the API Gateway.

  7. Token Exchange: The API Gateway exchanges the authorization code for an access token and optionally a refresh token for offline access.

  8. Token Storage: The API Gateway stores the access and refresh tokens in secure storage.

  9. Resource Access: The API Gateway uses the access token to access the third-party service on behalf of the user.

With this pattern, the user only needs to authenticate against the API Gateway, and we're never exposing any tokens to the user. This significantly enhances the security of our applications.

Benefits of the Token Handler Pattern

  1. Secure Authentication: The Token Handler Pattern keeps tokens away from the "front channel," preventing unauthorized access.

  2. Versatility: It enables "frontend" flows and allows for the implementation of asynchronous backend flows, such as data syncing, CRON jobs, and queue workers.

  3. Fine-Grained Access Control: The API Gateway only has as many permissions as the user has granted it, preventing over-reaching access.