sideara-image

Lorem ipsum dolor sit . Proin gravida nibh vel vealiquete sollicitudin, lorem quis bibendum auctonisilin sequat. Nam nec tellus a odio tincidunt auctor ornare.

Stay Connected & Follow us

What are you looking for?

Simply enter your keyword and we will help you find what you need.

Blog

Shielding Your API with Custom Authorizers

Do you feel like a fearless adventurer, braving the treacherous digital landscape in search of the ultimate API Gateway REST API security? Well, you’re not alone! In today’s world, protecting your APIs from unwanted access is crucial, and limiting access to specific IP addresses is a popular and effective approach. But fear not, fellow adventurer, for we have the solution you seek!

In this exciting blog post, we’ll show you how to wield the power of TypeScript to create a custom authorizer that will protect your API Gateway REST API like a mighty shield. With this tool in your arsenal, you’ll be able to take control of who has access to your APIs and keep your data safe from prying eyes. So grab your trusty keyboard and join us on this thrilling journey to secure your APIs with confidence!

Custom Authorizer

API Gateway offers a range of powerful tools for controlling access to your APIs, from IAM roles to Lambda authorizers. But for today’s adventure, we’ll be harnessing the power of custom authorizers to lock down our API Gateway REST API.

Custom authorizers are like the gatekeepers of your API, letting in only those who have the proper credentials. As the name suggests, they’re customizable to fit your specific security needs. And in this post, we’ll be using a custom authorizer to restrict access to our API Gateway REST API based on specific IP addresses.

With a custom authorizer in place, you’ll have greater control over who can access your API and what they can do with it. So buckle up, fearless adventurer, and let’s dive into the world of custom authorizers and IP filtering!

Implementation

We’ve covered the theory behind custom authorizers and IP filtering, but now it’s time to roll up our sleeves and dive into the implementation details!

In this thrilling chapter of our API security saga, we’ll be using TypeScript to craft a custom authorizer that allows only specific IP addresses to access our API Gateway REST API. This code will be your trusty sword and shield, protecting your API from unauthorized access and keeping your data safe and secure.

So grab your favorite code editor and get ready to write some serious code. We’ll guide you step-by-step through the implementation process, and by the end, you’ll have a custom authorizer that’s ready to defend your API against all manner of cyber threats. Let’s go!

import { APIGatewayAuthorizerEvent, APIGatewayAuthorizerResult, Context } from 'aws-lambda';

interface PolicyDocumentStatement {
  Action: string;
  Effect: string;
  Resource: string;
}

interface PolicyDocument {
  Version: string;
  Statement: PolicyDocumentStatement[];
}

interface AuthResponse {
  principalId: string;
  policyDocument: PolicyDocument;
}

export const handler = async (event: APIGatewayAuthorizerEvent, context: Context): Promise<APIGatewayAuthorizerResult> => {
  try {
    const ip_address = event.headers['X-Forwarded-For']?.split(',')[0] || event.requestContext.identity.sourceIp;
    const allowed_ips = ['192.168.1.1', '10.0.0.1', 'ADD_YOUR_IP_TO_TEST' ];
    if (!allowed_ips.includes(ip_address)) {
      return generatePolicy('user', 'Deny', event.methodArn);
    }
    return generatePolicy('user', 'Allow', event.methodArn);
  } catch (error) {
    console.error(error);
    return generatePolicy('user', 'Deny', event.methodArn);
  }
};

const generatePolicy = (principalId: string, effect: string, resource: string): AuthResponse => {
  const policyDocument: PolicyDocument = {
    Version: '2012-10-17',
    Statement: [
      {
        Action: 'execute-api:Invoke',
        Effect: effect,
        Resource: resource,
      },
    ],
  };
  return {
    principalId,
    policyDocument,
  };
};

Let’s go through this code in more detail.

IP Address Validation

First, we extract the IP address of the caller from the incoming event:

const ip_address = event.headers['X-Forwarded-For']?.split(',')[0] || event.requestContext.identity.sourceIp;

Note that we are using the X-Forwarded-For header to obtain the IP address of the user, but we are also checking the sourceIp field as a fallback. This is because when a user accesses your API Gateway REST API, their IP address is typically hidden behind a load balancer or proxy. The `X-Forwarded-For` header contains the user’s original IP address.

We use optional chaining (?.) to ensure that the X-Forwarded-For header exists and split it to obtain the user’s IP address. If the header does not exist, we use the sourceIp field as a fallback.

Next, we define an array of allowed IP addresses. We then check whether the IP address of the caller is in the list of allowed IP addresses:

const allowed_ips = ['192.168.1.1', '10.0.0.1', 'ADD_YOUR_IP_TO_TEST' ]
if (!allowed_ips.includes(ip_address)) {
  return generatePolicy('user', 'Deny', event.methodArn);
}

If the IP address of the caller is not on the list of allowed IP addresses, we return a policy that will deny the request.

Authorization Policy

If the IP address of the caller is in the list of allowed IP addresses, we generate an authorization policy document that allows access to the API:

return generatePolicy('user', 'Allow', event.methodArn);

The generatePolicy function generates an authorization policy document that allows access to the API:

const generatePolicy = (principalId: string, effect: string, resource: string): AuthResponse => {
  const policyDocument: PolicyDocument = {
    Version: '2012-10-17',
    Statement: [
      {
        Action: 'execute-api:Invoke',
        Effect: effect,
        Resource: resource,
      },
    ],
  };
  return {
    principalId,
    policyDocument,
  };
};

Testing

Now that you’ve braved the digital jungle and deployed your mighty custom authorizer to defend your API Gateway, it’s time to put it to the test! Will it stand strong against unauthorized access attempts? Let’s find out.

One way to test your custom authorizer is by making a request to your API Gateway REST API with an IP address that’s not on the list of allowed IPs. Imagine yourself as a daring hacker, attempting to breach your API Gateway defenses. But wait! Your custom authorizer is ready for the challenge and will respond with a bold 403 Forbidden message, sending the intruder running for cover.

But why stop there? With the power of the API Gateway console, you can test your custom authorizer even further. Navigate to your API Gateway API, select Authorizers from the sidebar, and behold the Test button next to your custom authorizer. With a click of a button, you can unleash a test event and witness your custom authorizer’s fierce response.

So go forth, brave defender of the API realm, and rest easy knowing your API Gateway is guarded by a custom authorizer that’s battle-tested and ready for anything.

Conclusion

Congratulations, intrepid explorer, you’ve successfully navigated the treacherous waters of API security and emerged victorious! By implementing a custom authorizer to restrict access to your API Gateway REST API, you’ve fortified your defenses and put the bad actors on notice.

But let’s not get complacent, bold adventurer. While IP address filtering is a formidable weapon in your security arsenal, it’s not invincible. The digital landscape is full of pitfalls and perils, and attackers are always on the lookout for vulnerabilities to exploit.

So keep your wits about you, fearless defender of the API realm. Stay vigilant, stay informed, and keep honing your security skills. With the right tools and mindset, you can create a fortress that even the most determined attackers will struggle to breach.

Now go forth, brave warrior, and continue your quest for API security glory!

Share
author avatar
Craftsmen Research Team
No Comments

Sorry, the comment form is closed at this time.