Use case: Protect APIs in your API Gateway

Why use API Access Control in your API Gateway

One of the great benefits of our API Access Control, is the decoupling of access-control enforcement and configuration from your own business logic code.

This decoupling removes the friction of adding, removing, and changing the access-control rules - so you no longer need to redeploy your code to apply those changes.

Not only that, you can use all of our entitlements capabilities to protect your APIs through permissions, features, plans and feature-flags.

When you integrate our SDK in your API Gateway, you get the benefit of few lines of code written once and in one place and that all it will take. After that the access-control configuration is shifted to our low-code platform.

Common uses

  1. Protect APIs with Permissions - classic RBAC (Role Based Access Control) use-case
  2. Protect APIs with Features and Plans - with different plans users can gets access to different APIs
  3. Protect APIs with Feature Flags - control access to your APIs using feature-flags.

In this use case, we’ll explore the use of API Access Control, with Express.js, utilizing Middleware to enforce API Access Control on all incoming requests.

Configure API Access Control

Configure Routes

Head over API Access Control page and for this example, we are going to create 2 APIs:

📘

For the simplicity of this use-case, we’ll not protect our APIs with Entitlements, we’ll only use “Allow” and “Block” policies.


  1. ANY /* Route (catch-all Route) - Represents all routes that are not configured, we’ll set its policy to “Block” - You can choose whatever policy suits you.
  2. GET /example Route - Represents one of the routes in our system, we’ll set its policy to “Allow”
image.png

Set Mode

API Access Control has 2 modes

  1. Monitoring (Default) - In this mode, the SDK will not enforce the access-control, it will only log the expected results, this is useful when first integrating with our product, and you want to watch how it behaves before actually enforcing the access-control
  2. Guard - In this mode, the SDK will enforce the access-control

Let’s go over the “Settings” tab, and toggle “Enforce API access control” on

image.png

Run Entitlements Agent

Follow these instructions to setup the agent to your current environment

Enforce API Access Control in your API Gateway

Now the magic begins.
In this part, we are going to create an Express.js server and use the Entitlements SDK to demonstrate how a few lines of code opens you up to a world of low-code/no-code Access Control.

Install Dependencies

npm install @frontegg/e10s-client @frontegg/client express

Express Server With Entitlements SDK

import express, {NextFunction, Request, Response} from 'express';
import {FronteggContext, IdentityClient} from '@frontegg/client';
import {EntitlementsClientFactory, RequestContextType} from '@frontegg/e10s-client';
import {tokenTypes} from '@frontegg/client/dist/src/clients/identity/types';

const app = express();

FronteggContext.init({
  FRONTEGG_CLIENT_ID: process.env.FRONTEGG_CLIENT_ID || '',
  FRONTEGG_API_KEY: process.env.FRONTEGG_API_KEY || '',
});

const identity = IdentityClient.getInstance();
const e10sClient = EntitlementsClientFactory.create({
  pdpHost: process.env.PDP_HOST as string,
});

// API Access Contorl Middleware
async function apiAccessControlMiddleware(req: Request, res: Response, next: NextFunction) {
  const token = req.header('Authorization')?.replace('Bearer ', '');
  const entity = await identity.validateToken(token as string);
  if (entity.type !== tokenTypes.UserToken) {
    throw Error('User Token Required');
  }
  const {result: isAllowed, justification} = await e10sClient.isEntitledTo(
    {userId: entity.sub, tenantId: entity.tenantId, permissions: entity.permissions, attributes: {}},
    {path: req.url, method: req.method, type: RequestContextType.Route},
  );

  if (isAllowed) {
    next();
  } else {
    res.status(403).send(justification);
  }
}

app.use(apiAccessControlMiddleware);

app.use('/example', (req, res, next) => {
  res.status(200).send('You gained access to the API');
});
app.use('/whatever', (req, res, next) => {
  res.status(200).send('You gained access to the API');
});

app.listen(process.env.PORT, () => {
  console.log('Server started', '[', process.env.PORT, ']');
});

For more information about the SDK - please visit https://github.com/frontegg/entitlements-client

Run and Test the API

With your server running, let’s perform the following requests

📘

Those requests are made with an Authorization token of a user that is logged in to our environment application


  1. GET /example

    Expected - Ok 200, since this API is configured to “Allow” in the portal.

  2. GET /whatever

    Expected - Forbidden 403, since this API is not configured, and we fallback to our catch-all route.