AWS APIGatewayv2 Authorizers
Introduction
API Gateway supports multiple mechanisms for controlling and managing access to your HTTP API. They are mainly classified into Lambda Authorizers, JWT authorizers, and standard AWS IAM roles and policies. More information is available at Controlling and managing access to an HTTP API.
HTTP APIs
Access control for HTTP APIs is managed by restricting which routes can be invoked via.
Authorizers and scopes can either be applied to the API, or specifically for each route.
Default Authorization
When using default authorization, all routes of the API will inherit the configuration.
In the example below, all routes will require the manage:books scope present in order to invoke the integration.
import { HttpJwtAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';
const issuer = 'https://test.us.auth0.com';
const authorizer = new HttpJwtAuthorizer('DefaultAuthorizer', issuer, {
jwtAudience: ['3131231'],
});
const api = new apigwv2.HttpApi(this, 'HttpApi', {
defaultAuthorizer: authorizer,
defaultAuthorizationScopes: ['manage:books'],
});
from aws_cdk.aws_apigatewayv2_authorizers import HttpJwtAuthorizer
issuer = "https://test.us.auth0.com"
authorizer = HttpJwtAuthorizer("DefaultAuthorizer", issuer,
jwt_audience=["3131231"]
)
api = apigwv2.HttpApi(self, "HttpApi",
default_authorizer=authorizer,
default_authorization_scopes=["manage:books"]
)
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpJwtAuthorizer;
String issuer = "https://test.us.auth0.com";
HttpJwtAuthorizer authorizer = HttpJwtAuthorizer.Builder.create("DefaultAuthorizer", issuer)
.jwtAudience(List.of("3131231"))
.build();
HttpApi api = HttpApi.Builder.create(this, "HttpApi")
.defaultAuthorizer(authorizer)
.defaultAuthorizationScopes(List.of("manage:books"))
.build();
using Amazon.CDK.AwsApigatewayv2Authorizers;
var issuer = "https://test.us.auth0.com";
var authorizer = new HttpJwtAuthorizer("DefaultAuthorizer", issuer, new HttpJwtAuthorizerProps {
JwtAudience = new [] { "3131231" }
});
var api = new HttpApi(this, "HttpApi", new HttpApiProps {
DefaultAuthorizer = authorizer,
DefaultAuthorizationScopes = new [] { "manage:books" }
});
import "github.com/aws/aws-cdk-go/awscdk"
issuer := "https://test.us.auth0.com"
authorizer := awscdk.NewHttpJwtAuthorizer(jsii.String("DefaultAuthorizer"), issuer, &HttpJwtAuthorizerProps{
JwtAudience: []*string{
jsii.String("3131231"),
},
})
api := apigwv2.NewHttpApi(this, jsii.String("HttpApi"), &HttpApiProps{
DefaultAuthorizer: authorizer,
DefaultAuthorizationScopes: []*string{
jsii.String("manage:books"),
},
})
Route Authorization
Authorization can also be configured for each Route. When a route authorization is configured, it takes precedence over default authorization.
The example below showcases default authorization, along with route authorization. It also shows how to remove authorization entirely for a route.
GET /booksandGET /books/{id}use the default authorizer settings on the apiPOST /bookswill require the['write:books']scopePOST /loginremoves the default authorizer (unauthenticated route)
import { HttpJwtAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';
import { HttpUrlIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
const issuer = 'https://test.us.auth0.com';
const authorizer = new HttpJwtAuthorizer('DefaultAuthorizer', issuer, {
jwtAudience: ['3131231'],
});
const api = new apigwv2.HttpApi(this, 'HttpApi', {
defaultAuthorizer: authorizer,
defaultAuthorizationScopes: ['read:books'],
});
api.addRoutes({
integration: new HttpUrlIntegration('BooksIntegration', 'https://get-books-proxy.example.com'),
path: '/books',
methods: [apigwv2.HttpMethod.GET],
});
api.addRoutes({
integration: new HttpUrlIntegration('BooksIdIntegration', 'https://get-books-proxy.example.com'),
path: '/books/{id}',
methods: [apigwv2.HttpMethod.GET],
});
api.addRoutes({
integration: new HttpUrlIntegration('BooksIntegration', 'https://get-books-proxy.example.com'),
path: '/books',
methods: [apigwv2.HttpMethod.POST],
authorizationScopes: ['write:books']
});
api.addRoutes({
integration: new HttpUrlIntegration('LoginIntegration', 'https://get-books-proxy.example.com'),
path: '/login',
methods: [apigwv2.HttpMethod.POST],
authorizer: new apigwv2.HttpNoneAuthorizer(),
});
from aws_cdk.aws_apigatewayv2_authorizers import HttpJwtAuthorizer
from aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration
issuer = "https://test.us.auth0.com"
authorizer = HttpJwtAuthorizer("DefaultAuthorizer", issuer,
jwt_audience=["3131231"]
)
api = apigwv2.HttpApi(self, "HttpApi",
default_authorizer=authorizer,
default_authorization_scopes=["read:books"]
)
api.add_routes(
integration=HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
path="/books",
methods=[apigwv2.HttpMethod.GET]
)
api.add_routes(
integration=HttpUrlIntegration("BooksIdIntegration", "https://get-books-proxy.example.com"),
path="/books/{id}",
methods=[apigwv2.HttpMethod.GET]
)
api.add_routes(
integration=HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
path="/books",
methods=[apigwv2.HttpMethod.POST],
authorization_scopes=["write:books"]
)
api.add_routes(
integration=HttpUrlIntegration("LoginIntegration", "https://get-books-proxy.example.com"),
path="/login",
methods=[apigwv2.HttpMethod.POST],
authorizer=apigwv2.HttpNoneAuthorizer()
)
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpJwtAuthorizer;
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
String issuer = "https://test.us.auth0.com";
HttpJwtAuthorizer authorizer = HttpJwtAuthorizer.Builder.create("DefaultAuthorizer", issuer)
.jwtAudience(List.of("3131231"))
.build();
HttpApi api = HttpApi.Builder.create(this, "HttpApi")
.defaultAuthorizer(authorizer)
.defaultAuthorizationScopes(List.of("read:books"))
.build();
api.addRoutes(AddRoutesOptions.builder()
.integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
.path("/books")
.methods(List.of(HttpMethod.GET))
.build());
api.addRoutes(AddRoutesOptions.builder()
.integration(new HttpUrlIntegration("BooksIdIntegration", "https://get-books-proxy.example.com"))
.path("/books/{id}")
.methods(List.of(HttpMethod.GET))
.build());
api.addRoutes(AddRoutesOptions.builder()
.integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
.path("/books")
.methods(List.of(HttpMethod.POST))
.authorizationScopes(List.of("write:books"))
.build());
api.addRoutes(AddRoutesOptions.builder()
.integration(new HttpUrlIntegration("LoginIntegration", "https://get-books-proxy.example.com"))
.path("/login")
.methods(List.of(HttpMethod.POST))
.authorizer(new HttpNoneAuthorizer())
.build());
using Amazon.CDK.AwsApigatewayv2Authorizers;
using Amazon.CDK.AwsApigatewayv2Integrations;
var issuer = "https://test.us.auth0.com";
var authorizer = new HttpJwtAuthorizer("DefaultAuthorizer", issuer, new HttpJwtAuthorizerProps {
JwtAudience = new [] { "3131231" }
});
var api = new HttpApi(this, "HttpApi", new HttpApiProps {
DefaultAuthorizer = authorizer,
DefaultAuthorizationScopes = new [] { "read:books" }
});
api.AddRoutes(new AddRoutesOptions {
Integration = new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
Path = "/books",
Methods = new [] { HttpMethod.GET }
});
api.AddRoutes(new AddRoutesOptions {
Integration = new HttpUrlIntegration("BooksIdIntegration", "https://get-books-proxy.example.com"),
Path = "/books/{id}",
Methods = new [] { HttpMethod.GET }
});
api.AddRoutes(new AddRoutesOptions {
Integration = new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
Path = "/books",
Methods = new [] { HttpMethod.POST },
AuthorizationScopes = new [] { "write:books" }
});
api.AddRoutes(new AddRoutesOptions {
Integration = new HttpUrlIntegration("LoginIntegration", "https://get-books-proxy.example.com"),
Path = "/login",
Methods = new [] { HttpMethod.POST },
Authorizer = new HttpNoneAuthorizer()
});
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
issuer := "https://test.us.auth0.com"
authorizer := awscdk.NewHttpJwtAuthorizer(jsii.String("DefaultAuthorizer"), issuer, &HttpJwtAuthorizerProps{
JwtAudience: []*string{
jsii.String("3131231"),
},
})
api := apigwv2.NewHttpApi(this, jsii.String("HttpApi"), &HttpApiProps{
DefaultAuthorizer: authorizer,
DefaultAuthorizationScopes: []*string{
jsii.String("read:books"),
},
})
api.AddRoutes(&AddRoutesOptions{
Integration: awscdk.NewHttpUrlIntegration(jsii.String("BooksIntegration"), jsii.String("https://get-books-proxy.example.com")),
Path: jsii.String("/books"),
Methods: []HttpMethod{
apigwv2.HttpMethod_GET,
},
})
api.AddRoutes(&AddRoutesOptions{
Integration: awscdk.NewHttpUrlIntegration(jsii.String("BooksIdIntegration"), jsii.String("https://get-books-proxy.example.com")),
Path: jsii.String("/books/{id}"),
Methods: []HttpMethod{
apigwv2.HttpMethod_GET,
},
})
api.AddRoutes(&AddRoutesOptions{
Integration: awscdk.NewHttpUrlIntegration(jsii.String("BooksIntegration"), jsii.String("https://get-books-proxy.example.com")),
Path: jsii.String("/books"),
Methods: []HttpMethod{
apigwv2.HttpMethod_POST,
},
AuthorizationScopes: []*string{
jsii.String("write:books"),
},
})
api.AddRoutes(&AddRoutesOptions{
Integration: awscdk.NewHttpUrlIntegration(jsii.String("LoginIntegration"), jsii.String("https://get-books-proxy.example.com")),
Path: jsii.String("/login"),
Methods: []HttpMethod{
apigwv2.HttpMethod_POST,
},
Authorizer: apigwv2.NewHttpNoneAuthorizer(),
})
JWT Authorizers
JWT authorizers allow the use of JSON Web Tokens (JWTs) as part of OpenID Connect and OAuth 2.0 frameworks to allow and restrict clients from accessing HTTP APIs.
When configured, API Gateway validates the JWT submitted by the client, and allows or denies access based on its content.
The location of the token is defined by the identitySource which defaults to the HTTP Authorization header. However it also supports a number of other options. It then decodes the JWT and validates the signature and claims, against the options defined in the authorizer and route (scopes). For more information check the JWT Authorizer documentation.
Clients that fail authorization are presented with either 2 responses:
401 - Unauthorized- When the JWT validation fails403 - Forbidden- When the JWT validation is successful but the required scopes are not met
import { HttpJwtAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';
import { HttpUrlIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
const issuer = 'https://test.us.auth0.com';
const authorizer = new HttpJwtAuthorizer('BooksAuthorizer', issuer, {
jwtAudience: ['3131231'],
});
const api = new apigwv2.HttpApi(this, 'HttpApi');
api.addRoutes({
integration: new HttpUrlIntegration('BooksIntegration', 'https://get-books-proxy.example.com'),
path: '/books',
authorizer,
});
from aws_cdk.aws_apigatewayv2_authorizers import HttpJwtAuthorizer
from aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration
issuer = "https://test.us.auth0.com"
authorizer = HttpJwtAuthorizer("BooksAuthorizer", issuer,
jwt_audience=["3131231"]
)
api = apigwv2.HttpApi(self, "HttpApi")
api.add_routes(
integration=HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
path="/books",
authorizer=authorizer
)
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpJwtAuthorizer;
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
String issuer = "https://test.us.auth0.com";
HttpJwtAuthorizer authorizer = HttpJwtAuthorizer.Builder.create("BooksAuthorizer", issuer)
.jwtAudience(List.of("3131231"))
.build();
HttpApi api = new HttpApi(this, "HttpApi");
api.addRoutes(AddRoutesOptions.builder()
.integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
.path("/books")
.authorizer(authorizer)
.build());
using Amazon.CDK.AwsApigatewayv2Authorizers;
using Amazon.CDK.AwsApigatewayv2Integrations;
var issuer = "https://test.us.auth0.com";
var authorizer = new HttpJwtAuthorizer("BooksAuthorizer", issuer, new HttpJwtAuthorizerProps {
JwtAudience = new [] { "3131231" }
});
var api = new HttpApi(this, "HttpApi");
api.AddRoutes(new AddRoutesOptions {
Integration = new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
Path = "/books",
Authorizer = authorizer
});
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
issuer := "https://test.us.auth0.com"
authorizer := awscdk.NewHttpJwtAuthorizer(jsii.String("BooksAuthorizer"), issuer, &HttpJwtAuthorizerProps{
JwtAudience: []*string{
jsii.String("3131231"),
},
})
api := apigwv2.NewHttpApi(this, jsii.String("HttpApi"))
api.AddRoutes(&AddRoutesOptions{
Integration: awscdk.NewHttpUrlIntegration(jsii.String("BooksIntegration"), jsii.String("https://get-books-proxy.example.com")),
Path: jsii.String("/books"),
Authorizer: Authorizer,
})
User Pool Authorizer
User Pool Authorizer is a type of JWT Authorizer that uses a Cognito user pool and app client to control who can access your API. After a successful authorization from the app client, the generated access token will be used as the JWT.
Clients accessing an API that uses a user pool authorizer must first sign in to a user pool and obtain an identity or access token. They must then use this token in the specified identitySource for the API call. More information is available at using Amazon Cognito user pools as authorizer.
import * as cognito from 'aws-cdk-lib/aws-cognito';
import { HttpUserPoolAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';
import { HttpUrlIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
const userPool = new cognito.UserPool(this, 'UserPool');
const authorizer = new HttpUserPoolAuthorizer('BooksAuthorizer', userPool);
const api = new apigwv2.HttpApi(this, 'HttpApi');
api.addRoutes({
integration: new HttpUrlIntegration('BooksIntegration', 'https://get-books-proxy.example.com'),
path: '/books',
authorizer,
});
import aws_cdk.aws_cognito as cognito
from aws_cdk.aws_apigatewayv2_authorizers import HttpUserPoolAuthorizer
from aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration
user_pool = cognito.UserPool(self, "UserPool")
authorizer = HttpUserPoolAuthorizer("BooksAuthorizer", user_pool)
api = apigwv2.HttpApi(self, "HttpApi")
api.add_routes(
integration=HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
path="/books",
authorizer=authorizer
)
import software.amazon.awscdk.services.cognito.*;
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpUserPoolAuthorizer;
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
UserPool userPool = new UserPool(this, "UserPool");
HttpUserPoolAuthorizer authorizer = new HttpUserPoolAuthorizer("BooksAuthorizer", userPool);
HttpApi api = new HttpApi(this, "HttpApi");
api.addRoutes(AddRoutesOptions.builder()
.integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
.path("/books")
.authorizer(authorizer)
.build());
using Amazon.CDK.AWS.Cognito;
using Amazon.CDK.AwsApigatewayv2Authorizers;
using Amazon.CDK.AwsApigatewayv2Integrations;
var userPool = new UserPool(this, "UserPool");
var authorizer = new HttpUserPoolAuthorizer("BooksAuthorizer", userPool);
var api = new HttpApi(this, "HttpApi");
api.AddRoutes(new AddRoutesOptions {
Integration = new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
Path = "/books",
Authorizer = authorizer
});
import cognito "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
userPool := cognito.NewUserPool(this, jsii.String("UserPool"))
authorizer := awscdk.NewHttpUserPoolAuthorizer(jsii.String("BooksAuthorizer"), userPool)
api := apigwv2.NewHttpApi(this, jsii.String("HttpApi"))
api.AddRoutes(&AddRoutesOptions{
Integration: awscdk.NewHttpUrlIntegration(jsii.String("BooksIntegration"), jsii.String("https://get-books-proxy.example.com")),
Path: jsii.String("/books"),
Authorizer: Authorizer,
})
Lambda Authorizers
Lambda authorizers use a Lambda function to control access to your HTTP API. When a client calls your API, API Gateway invokes your Lambda function and uses the response to determine whether the client can access your API.
Lambda authorizers depending on their response, fall into either two types - Simple or IAM. You can learn about differences here.
If the Lambda function is in another account, you need to provide an IAM role to the authorizer that has permission to invoke the Lambda function.
import { HttpLambdaAuthorizer, HttpLambdaResponseType } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';
import { HttpUrlIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
// This function handles your auth logic
declare const authHandler: lambda.Function;
// This role will be used to invoke the Lambda function
declare const role: iam.Role;
const authorizer = new HttpLambdaAuthorizer('BooksAuthorizer', authHandler, {
responseTypes: [HttpLambdaResponseType.SIMPLE], // Define if returns simple and/or iam response
role, // Set role if the Lambda function is in another account
});
const api = new apigwv2.HttpApi(this, 'HttpApi');
api.addRoutes({
integration: new HttpUrlIntegration('BooksIntegration', 'https://get-books-proxy.example.com'),
path: '/books',
authorizer,
});
from aws_cdk.aws_apigatewayv2_authorizers import HttpLambdaAuthorizer, HttpLambdaResponseType
from aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration
# This function handles your auth logic
# auth_handler: lambda.Function
# This role will be used to invoke the Lambda function
# role: iam.Role
authorizer = HttpLambdaAuthorizer("BooksAuthorizer", auth_handler,
response_types=[HttpLambdaResponseType.SIMPLE], # Define if returns simple and/or iam response
role=role
)
api = apigwv2.HttpApi(self, "HttpApi")
api.add_routes(
integration=HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
path="/books",
authorizer=authorizer
)
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpLambdaAuthorizer;
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpLambdaResponseType;
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
// This function handles your auth logic
Function authHandler;
// This role will be used to invoke the Lambda function
Role role;
HttpLambdaAuthorizer authorizer = HttpLambdaAuthorizer.Builder.create("BooksAuthorizer", authHandler)
.responseTypes(List.of(HttpLambdaResponseType.SIMPLE)) // Define if returns simple and/or iam response
.role(role)
.build();
HttpApi api = new HttpApi(this, "HttpApi");
api.addRoutes(AddRoutesOptions.builder()
.integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
.path("/books")
.authorizer(authorizer)
.build());
using Amazon.CDK.AwsApigatewayv2Authorizers;
using Amazon.CDK.AwsApigatewayv2Integrations;
// This function handles your auth logic
Function authHandler;
// This role will be used to invoke the Lambda function
Role role;
var authorizer = new HttpLambdaAuthorizer("BooksAuthorizer", authHandler, new HttpLambdaAuthorizerProps {
ResponseTypes = new [] { HttpLambdaResponseType.SIMPLE }, // Define if returns simple and/or iam response
Role = role
});
var api = new HttpApi(this, "HttpApi");
api.AddRoutes(new AddRoutesOptions {
Integration = new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
Path = "/books",
Authorizer = authorizer
});
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
// This function handles your auth logic
var authHandler Function
// This role will be used to invoke the Lambda function
var role Role
authorizer := awscdk.NewHttpLambdaAuthorizer(jsii.String("BooksAuthorizer"), authHandler, &HttpLambdaAuthorizerProps{
ResponseTypes: []HttpLambdaResponseType{
awscdk.HttpLambdaResponseType_SIMPLE,
},
// Define if returns simple and/or iam response
Role: Role,
})
api := apigwv2.NewHttpApi(this, jsii.String("HttpApi"))
api.AddRoutes(&AddRoutesOptions{
Integration: awscdk.NewHttpUrlIntegration(jsii.String("BooksIntegration"), jsii.String("https://get-books-proxy.example.com")),
Path: jsii.String("/books"),
Authorizer: Authorizer,
})
IAM Authorizers
API Gateway supports IAM via the included HttpIamAuthorizer and grant syntax:
import { HttpIamAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';
import { HttpUrlIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
declare const principal: iam.AnyPrincipal;
const authorizer = new HttpIamAuthorizer();
const httpApi = new apigwv2.HttpApi(this, 'HttpApi', {
defaultAuthorizer: authorizer,
});
const routes = httpApi.addRoutes({
integration: new HttpUrlIntegration('BooksIntegration', 'https://get-books-proxy.example.com'),
path: '/books/{book}',
});
routes[0].grantInvoke(principal);
from aws_cdk.aws_apigatewayv2_authorizers import HttpIamAuthorizer
from aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration
# principal: iam.AnyPrincipal
authorizer = HttpIamAuthorizer()
http_api = apigwv2.HttpApi(self, "HttpApi",
default_authorizer=authorizer
)
routes = http_api.add_routes(
integration=HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
path="/books/{book}"
)
routes[0].grant_invoke(principal)
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpIamAuthorizer;
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
AnyPrincipal principal;
HttpIamAuthorizer authorizer = new HttpIamAuthorizer();
HttpApi httpApi = HttpApi.Builder.create(this, "HttpApi")
.defaultAuthorizer(authorizer)
.build();
HttpRoute[] routes = httpApi.addRoutes(AddRoutesOptions.builder()
.integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
.path("/books/{book}")
.build());
routes[0].grantInvoke(principal);
using Amazon.CDK.AwsApigatewayv2Authorizers;
using Amazon.CDK.AwsApigatewayv2Integrations;
AnyPrincipal principal;
var authorizer = new HttpIamAuthorizer();
var httpApi = new HttpApi(this, "HttpApi", new HttpApiProps {
DefaultAuthorizer = authorizer
});
var routes = httpApi.AddRoutes(new AddRoutesOptions {
Integration = new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
Path = "/books/{book}"
});
routes[0].GrantInvoke(principal);
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
var principal AnyPrincipal
authorizer := awscdk.NewHttpIamAuthorizer()
httpApi := apigwv2.NewHttpApi(this, jsii.String("HttpApi"), &HttpApiProps{
DefaultAuthorizer: authorizer,
})
routes := httpApi.AddRoutes(&AddRoutesOptions{
Integration: awscdk.NewHttpUrlIntegration(jsii.String("BooksIntegration"), jsii.String("https://get-books-proxy.example.com")),
Path: jsii.String("/books/{book}"),
})
routes[0].GrantInvoke(principal)
WebSocket APIs
You can set an authorizer to your WebSocket API's $connect route to control access to your API.
Lambda Authorizer
Lambda authorizers use a Lambda function to control access to your WebSocket API. When a client connects to your API, API Gateway invokes your Lambda function and uses the response to determine whether the client can access your API.
import { WebSocketLambdaAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';
import { WebSocketLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
// This function handles your auth logic
declare const authHandler: lambda.Function;
// This function handles your WebSocket requests
declare const handler: lambda.Function;
const authorizer = new WebSocketLambdaAuthorizer('Authorizer', authHandler);
const integration = new WebSocketLambdaIntegration(
'Integration',
handler,
);
new apigwv2.WebSocketApi(this, 'WebSocketApi', {
connectRouteOptions: {
integration,
authorizer,
},
});
from aws_cdk.aws_apigatewayv2_authorizers import WebSocketLambdaAuthorizer
from aws_cdk.aws_apigatewayv2_integrations import WebSocketLambdaIntegration
# This function handles your auth logic
# auth_handler: lambda.Function
# This function handles your WebSocket requests
# handler: lambda.Function
authorizer = WebSocketLambdaAuthorizer("Authorizer", auth_handler)
integration = WebSocketLambdaIntegration("Integration", handler)
apigwv2.WebSocketApi(self, "WebSocketApi",
connect_route_options=apigwv2.WebSocketRouteOptions(
integration=integration,
authorizer=authorizer
)
)
import software.amazon.awscdk.aws_apigatewayv2_authorizers.WebSocketLambdaAuthorizer;
import software.amazon.awscdk.aws_apigatewayv2_integrations.WebSocketLambdaIntegration;
// This function handles your auth logic
Function authHandler;
// This function handles your WebSocket requests
Function handler;
WebSocketLambdaAuthorizer authorizer = new WebSocketLambdaAuthorizer("Authorizer", authHandler);
WebSocketLambdaIntegration integration = new WebSocketLambdaIntegration("Integration", handler);
WebSocketApi.Builder.create(this, "WebSocketApi")
.connectRouteOptions(WebSocketRouteOptions.builder()
.integration(integration)
.authorizer(authorizer)
.build())
.build();
using Amazon.CDK.AwsApigatewayv2Authorizers;
using Amazon.CDK.AwsApigatewayv2Integrations;
// This function handles your auth logic
Function authHandler;
// This function handles your WebSocket requests
Function handler;
var authorizer = new WebSocketLambdaAuthorizer("Authorizer", authHandler);
var integration = new WebSocketLambdaIntegration("Integration", handler);
new WebSocketApi(this, "WebSocketApi", new WebSocketApiProps {
ConnectRouteOptions = new WebSocketRouteOptions {
Integration = integration,
Authorizer = authorizer
}
});
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
// This function handles your auth logic
var authHandler Function
// This function handles your WebSocket requests
var handler Function
authorizer := awscdk.NewWebSocketLambdaAuthorizer(jsii.String("Authorizer"), authHandler)
integration := awscdk.NewWebSocketLambdaIntegration(jsii.String("Integration"), handler)
apigwv2.NewWebSocketApi(this, jsii.String("WebSocketApi"), &WebSocketApiProps{
ConnectRouteOptions: &WebSocketRouteOptions{
Integration: *Integration,
Authorizer: *Authorizer,
},
})
IAM Authorizer
IAM authorizers can be used to allow identity-based access to your WebSocket API.
import { WebSocketIamAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';
import { WebSocketLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
// This function handles your connect route
declare const connectHandler: lambda.Function;
const webSocketApi = new apigwv2.WebSocketApi(this, 'WebSocketApi');
webSocketApi.addRoute('$connect', {
integration: new WebSocketLambdaIntegration('Integration', connectHandler),
authorizer: new WebSocketIamAuthorizer()
});
// Create an IAM user (identity)
const user = new iam.User(this, 'User');
const webSocketArn = Stack.of(this).formatArn({
service: 'execute-api',
resource: webSocketApi.apiId,
});
// Grant access to the IAM user
user.attachInlinePolicy(new iam.Policy(this, 'AllowInvoke', {
statements: [
new iam.PolicyStatement({
actions: ['execute-api:Invoke'],
effect: iam.Effect.ALLOW,
resources: [webSocketArn],
}),
],
}));
from aws_cdk.aws_apigatewayv2_authorizers import WebSocketIamAuthorizer
from aws_cdk.aws_apigatewayv2_integrations import WebSocketLambdaIntegration
# This function handles your connect route
# connect_handler: lambda.Function
web_socket_api = apigwv2.WebSocketApi(self, "WebSocketApi")
web_socket_api.add_route("$connect",
integration=WebSocketLambdaIntegration("Integration", connect_handler),
authorizer=WebSocketIamAuthorizer()
)
# Create an IAM user (identity)
user = iam.User(self, "User")
web_socket_arn = Stack.of(self).format_arn(
service="execute-api",
resource=web_socket_api.api_id
)
# Grant access to the IAM user
user.attach_inline_policy(iam.Policy(self, "AllowInvoke",
statements=[
iam.PolicyStatement(
actions=["execute-api:Invoke"],
effect=iam.Effect.ALLOW,
resources=[web_socket_arn]
)
]
))
import software.amazon.awscdk.aws_apigatewayv2_authorizers.WebSocketIamAuthorizer;
import software.amazon.awscdk.aws_apigatewayv2_integrations.WebSocketLambdaIntegration;
// This function handles your connect route
Function connectHandler;
WebSocketApi webSocketApi = new WebSocketApi(this, "WebSocketApi");
webSocketApi.addRoute("$connect", WebSocketRouteOptions.builder()
.integration(new WebSocketLambdaIntegration("Integration", connectHandler))
.authorizer(new WebSocketIamAuthorizer())
.build());
// Create an IAM user (identity)
User user = new User(this, "User");
String webSocketArn = Stack.of(this).formatArn(ArnComponents.builder()
.service("execute-api")
.resource(webSocketApi.getApiId())
.build());
// Grant access to the IAM user
user.attachInlinePolicy(Policy.Builder.create(this, "AllowInvoke")
.statements(List.of(
PolicyStatement.Builder.create()
.actions(List.of("execute-api:Invoke"))
.effect(Effect.ALLOW)
.resources(List.of(webSocketArn))
.build()))
.build());
using Amazon.CDK.AwsApigatewayv2Authorizers;
using Amazon.CDK.AwsApigatewayv2Integrations;
// This function handles your connect route
Function connectHandler;
var webSocketApi = new WebSocketApi(this, "WebSocketApi");
webSocketApi.AddRoute("$connect", new WebSocketRouteOptions {
Integration = new WebSocketLambdaIntegration("Integration", connectHandler),
Authorizer = new WebSocketIamAuthorizer()
});
// Create an IAM user (identity)
var user = new User(this, "User");
var webSocketArn = Stack.Of(this).FormatArn(new ArnComponents {
Service = "execute-api",
Resource = webSocketApi.ApiId
});
// Grant access to the IAM user
user.AttachInlinePolicy(new Policy(this, "AllowInvoke", new PolicyProps {
Statements = new [] {
new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "execute-api:Invoke" },
Effect = Effect.ALLOW,
Resources = new [] { webSocketArn }
}) }
}));
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
// This function handles your connect route
var connectHandler Function
webSocketApi := apigwv2.NewWebSocketApi(this, jsii.String("WebSocketApi"))
webSocketApi.AddRoute(jsii.String("$connect"), &WebSocketRouteOptions{
Integration: awscdk.NewWebSocketLambdaIntegration(jsii.String("Integration"), connectHandler),
Authorizer: awscdk.NewWebSocketIamAuthorizer(),
})
// Create an IAM user (identity)
user := iam.NewUser(this, jsii.String("User"))
webSocketArn := awscdk.stack_Of(this).FormatArn(&ArnComponents{
Service: jsii.String("execute-api"),
Resource: webSocketApi.ApiId,
})
// Grant access to the IAM user
user.AttachInlinePolicy(iam.NewPolicy(this, jsii.String("AllowInvoke"), &PolicyProps{
Statements: []PolicyStatement{
iam.NewPolicyStatement(&PolicyStatementProps{
Actions: []*string{
jsii.String("execute-api:Invoke"),
},
Effect: iam.Effect_ALLOW,
Resources: []*string{
webSocketArn,
},
}),
},
}))
Import Issues
jsiirc.json file is missing during the stablization process of this module, which caused import issues for DotNet and Java users who attempt to use this module. Unfortunately, to guarantee backward compatibility, we cannot simply correct the namespace for DotNet or package for Java. The following outlines the workaround.
DotNet Namespace
Instead of the conventional namespace Amazon.CDK.AWS.Apigatewayv2.Authorizers, you would need to use the following namespace:
using Amazon.CDK.AwsApigatewayv2Authorizers;;
Java Package
Instead of conventional package import software.amazon.awscdk.services.apigatewayv2_authorizers.*, you would need to use the following package:
import software.amazon.awscdk.aws_apigatewayv2_authorizers.*;
// If you want to import a specific construct
import software.amazon.awscdk.aws_apigatewayv2_authorizers.WebSocketIamAuthorizer;
Export HTTP Authorizer Id
You can retrieve the authorizer's id once it has been bound to a route to export the value.
HttpAuthorizer.fromHttpAuthorizerAttributes
import { HttpLambdaAuthorizer, HttpLambdaResponseType } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';
import { HttpUrlIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
import { CfnOutput } from 'aws-cdk-lib';
// This function handles your auth logic
declare const authHandler: lambda.Function;
const authorizer = new HttpLambdaAuthorizer('BooksAuthorizer', authHandler, {
responseTypes: [HttpLambdaResponseType.SIMPLE], // Define if returns simple and/or iam response
});
const api = new apigwv2.HttpApi(this, 'HttpApi');
api.addRoutes({
integration: new HttpUrlIntegration('BooksIntegration', 'https://get-books-proxy.example.com'),
path: '/books',
authorizer,
});
// You can only access authorizerId after it's been bound to a route
// In this example we expect use CfnOutput
new CfnOutput(this, 'authorizerId', { value: authorizer.authorizerId });
new CfnOutput(this, 'authorizerType', { value: authorizer.authorizationType });
from aws_cdk.aws_apigatewayv2_authorizers import HttpLambdaAuthorizer, HttpLambdaResponseType
from aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration
from aws_cdk import CfnOutput
# This function handles your auth logic
# auth_handler: lambda.Function
authorizer = HttpLambdaAuthorizer("BooksAuthorizer", auth_handler,
response_types=[HttpLambdaResponseType.SIMPLE]
)
api = apigwv2.HttpApi(self, "HttpApi")
api.add_routes(
integration=HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
path="/books",
authorizer=authorizer
)
# You can only access authorizerId after it's been bound to a route
# In this example we expect use CfnOutput
CfnOutput(self, "authorizerId", value=authorizer.authorizer_id)
CfnOutput(self, "authorizerType", value=authorizer.authorization_type)
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpLambdaAuthorizer;
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpLambdaResponseType;
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
import software.amazon.awscdk.CfnOutput;
// This function handles your auth logic
Function authHandler;
HttpLambdaAuthorizer authorizer = HttpLambdaAuthorizer.Builder.create("BooksAuthorizer", authHandler)
.responseTypes(List.of(HttpLambdaResponseType.SIMPLE))
.build();
HttpApi api = new HttpApi(this, "HttpApi");
api.addRoutes(AddRoutesOptions.builder()
.integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
.path("/books")
.authorizer(authorizer)
.build());
// You can only access authorizerId after it's been bound to a route
// In this example we expect use CfnOutput
// You can only access authorizerId after it's been bound to a route
// In this example we expect use CfnOutput
CfnOutput.Builder.create(this, "authorizerId").value(authorizer.getAuthorizerId()).build();
CfnOutput.Builder.create(this, "authorizerType").value(authorizer.getAuthorizationType()).build();
using Amazon.CDK.AwsApigatewayv2Authorizers;
using Amazon.CDK.AwsApigatewayv2Integrations;
using Amazon.CDK;
// This function handles your auth logic
Function authHandler;
var authorizer = new HttpLambdaAuthorizer("BooksAuthorizer", authHandler, new HttpLambdaAuthorizerProps {
ResponseTypes = new [] { HttpLambdaResponseType.SIMPLE }
});
var api = new HttpApi(this, "HttpApi");
api.AddRoutes(new AddRoutesOptions {
Integration = new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"),
Path = "/books",
Authorizer = authorizer
});
// You can only access authorizerId after it's been bound to a route
// In this example we expect use CfnOutput
// You can only access authorizerId after it's been bound to a route
// In this example we expect use CfnOutput
new CfnOutput(this, "authorizerId", new CfnOutputProps { Value = authorizer.AuthorizerId });
new CfnOutput(this, "authorizerType", new CfnOutputProps { Value = authorizer.AuthorizationType });
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
// This function handles your auth logic
var authHandler Function
authorizer := awscdk.NewHttpLambdaAuthorizer(jsii.String("BooksAuthorizer"), authHandler, &HttpLambdaAuthorizerProps{
ResponseTypes: []HttpLambdaResponseType{
awscdk.HttpLambdaResponseType_SIMPLE,
},
})
api := apigwv2.NewHttpApi(this, jsii.String("HttpApi"))
api.AddRoutes(&AddRoutesOptions{
Integration: awscdk.NewHttpUrlIntegration(jsii.String("BooksIntegration"), jsii.String("https://get-books-proxy.example.com")),
Path: jsii.String("/books"),
Authorizer: Authorizer,
})
// You can only access authorizerId after it's been bound to a route
// In this example we expect use CfnOutput
// You can only access authorizerId after it's been bound to a route
// In this example we expect use CfnOutput
awscdk.NewCfnOutput(this, jsii.String("authorizerId"), &CfnOutputProps{
Value: authorizer.authorizerId,
})
awscdk.NewCfnOutput(this, jsii.String("authorizerType"), &CfnOutputProps{
Value: authorizer.AuthorizationType,
})
Import an existing HTTP Authorizer
If you want to import av existing HTTP Authorizer you simply provide the authorizer id and authorizer type used when the authorizer was created.
import { HttpAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2';
import { Fn } from 'aws-cdk-lib'
const authorizerId = Fn.importValue('authorizerId');
const authorizerType = Fn.importValue('authorizerType');
const authorizer = HttpAuthorizer.fromHttpAuthorizerAttributes(this, 'HttpAuthorizer', {
authorizerId,
authorizerType
});
from aws_cdk.aws_apigatewayv2 import HttpAuthorizer
from aws_cdk import Fn
authorizer_id = Fn.import_value("authorizerId")
authorizer_type = Fn.import_value("authorizerType")
authorizer = HttpAuthorizer.from_http_authorizer_attributes(self, "HttpAuthorizer",
authorizer_id=authorizer_id,
authorizer_type=authorizer_type
)
import software.amazon.awscdk.services.apigatewayv2.HttpAuthorizer;
import software.amazon.awscdk.Fn;
String authorizerId = Fn.importValue("authorizerId");
String authorizerType = Fn.importValue("authorizerType");
IHttpRouteAuthorizer authorizer = HttpAuthorizer.fromHttpAuthorizerAttributes(this, "HttpAuthorizer", HttpAuthorizerAttributes.builder()
.authorizerId(authorizerId)
.authorizerType(authorizerType)
.build());
using Amazon.CDK.AWS.Apigatewayv2;
using Amazon.CDK;
var authorizerId = Fn.ImportValue("authorizerId");
var authorizerType = Fn.ImportValue("authorizerType");
var authorizer = HttpAuthorizer.FromHttpAuthorizerAttributes(this, "HttpAuthorizer", new HttpAuthorizerAttributes {
AuthorizerId = authorizerId,
AuthorizerType = authorizerType
});
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
authorizerId := awscdk.Fn_ImportValue(jsii.String("authorizerId"))
authorizerType := awscdk.Fn_ImportValue(jsii.String("authorizerType"))
authorizer := awscdk.HttpAuthorizer_FromHttpAuthorizerAttributes(this, jsii.String("HttpAuthorizer"), &HttpAuthorizerAttributes{
AuthorizerId: jsii.String(AuthorizerId),
AuthorizerType: jsii.String(AuthorizerType),
})
Types
| Name | Kind | Summary |
|---|---|---|
HttpIamAuthorizer | Class | Authorize HTTP API Routes with IAM. |
HttpJwtAuthorizer | Class | Authorize Http Api routes on whether the requester is registered as part of an AWS Cognito user pool. |
HttpJwtAuthorizerProps | Struct | Properties to initialize HttpJwtAuthorizer. |
HttpLambdaAuthorizer | Class | Authorize Http Api routes via a lambda function. |
HttpLambdaAuthorizerProps | Struct | Properties to initialize HttpTokenAuthorizer. |
HttpLambdaResponseType | Enum | Specifies the type responses the lambda returns. |
HttpUserPoolAuthorizer | Class | Authorize Http Api routes on whether the requester is registered as part of an AWS Cognito user pool. |
HttpUserPoolAuthorizerProps | Struct | Properties to initialize HttpUserPoolAuthorizer. |
WebSocketIamAuthorizer | Class | Authorize WebSocket API Routes with IAM. |
WebSocketLambdaAuthorizer | Class | Authorize WebSocket Api routes via a lambda function. |
WebSocketLambdaAuthorizerProps | Struct | Properties to initialize WebSocketTokenAuthorizer. |