AWS API Gateway Tutorial, Part 4: Secure the API Using Custom Authorizers

In part 1, you configured Auth0 for use with API Gateway, in part 2, you configured an API using API Gateway, and in part 3, you created the custom authorizer that can be used to retrieve the appropriate policies when your API receives an access request. In this part of the tutorial, we will show you how to use the custom authorizer to secure your API's endpoints.

Configure API Gateway Resources to use the Custom Authorizer

Log in to AWS and navigate to the API Gateway Console.

Custom authorizers are set on a method by method basis; if you want to secure multiple methods using a single authorizer, you'll need to repeat the following instructions for each method.

Open the PetStore API we created in part 2 of this tutorial. Under the Resource tree in the center pane, select the GET method under the /pets resource.

Select Method Request.

Under Settings, click the pencil icon to the right Authorization and choose the jwt-rsa-custom-authorizer custom authorizer you created in part 3.

Click the check mark icon to save your choice of custom authorizer. Make sure the API Key Required field is set to false.

Deploy the API

To make your changes public, you'll need to deploy your API.

If successful, you'll be redirected to the Test Stage Editor. Copy down the Invoke URL provided in the blue ribbon at the top, since you'll need this to test your deployment.

Test Your Deployment

You can test your deployment by making a GET call to the Invoke URL you copied in the previous step.


curl --request GET \
  --url https://your_invoke_url/pets \
  --header 'authorization: Bearer TOKEN'
var client = new RestClient("https://your_invoke_url/pets");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer TOKEN");
IRestResponse response = client.Execute(request);
package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {

	url := "https://your_invoke_url/pets"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Add("authorization", "Bearer TOKEN")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
HttpResponse<String> response = Unirest.get("https://your_invoke_url/pets")
  .header("authorization", "Bearer TOKEN")
  .asString();
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://your_invoke_url/pets",
  "method": "GET",
  "headers": {
    "authorization": "Bearer TOKEN"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
var request = require("request");

var options = { method: 'GET',
  url: 'https://your_invoke_url/pets',
  headers: { authorization: 'Bearer TOKEN' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
#import <Foundation/Foundation.h>

NSDictionary *headers = @{ @"authorization": @"Bearer TOKEN" };

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://your_invoke_url/pets"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[request setHTTPMethod:@"GET"];
[request setAllHTTPHeaderFields:headers];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {
                                                    NSLog(@"%@", error);
                                                } else {
                                                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                    NSLog(@"%@", httpResponse);
                                                }
                                            }];
[dataTask resume];
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://your_invoke_url/pets",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "authorization: Bearer TOKEN"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
import http.client

conn = http.client.HTTPSConnection("your_invoke_url")

headers = { 'authorization': "Bearer TOKEN" }

conn.request("GET", "/pets", headers=headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))
require 'uri'
require 'net/http'

url = URI("https://your_invoke_url/pets")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Get.new(url)
request["authorization"] = 'Bearer TOKEN'

response = http.request(request)
puts response.read_body
import Foundation

let headers = ["authorization": "Bearer TOKEN"]

var request = NSMutableURLRequest(URL: NSURL(string: "https://your_invoke_url/pets")!,
                                        cachePolicy: .UseProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.HTTPMethod = "GET"
request.allHTTPHeaderFields = headers

let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    println(error)
  } else {
    let httpResponse = response as? NSHTTPURLResponse
    println(httpResponse)
  }
})

dataTask.resume()

Summary

In this tutorial, you have

  1. Configured Auth0 for use with API Gateway
  2. Imported an API for use with API Gateway
  3. Created a custom authorizer to secure your API's endpoints, which required working with AWS IAM and Lambda
  4. Secured your API with your custom authorizer