Package software.amazon.awscdk.aws_apigatewayv2_authorizers
AWS APIGatewayv2 Authorizers
Table of Contents
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 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();
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 /books
andGET /books/{id}
use the default authorizer settings on the apiPOST /books
will require the['write:books']
scopePOST /login
removes the default authorizer (unauthenticated route)
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());
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 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());
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 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());
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.
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; 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());
IAM Authorizers
API Gateway supports IAM via the included HttpIamAuthorizer
and grant syntax:
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);
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 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();
IAM Authorizer
IAM authorizers can be used to allow identity-based access to your WebSocket API.
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());
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 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();
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 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());
-
ClassDescriptionAuthorize HTTP API Routes with IAM.Authorize Http Api routes on whether the requester is registered as part of an AWS Cognito user pool.A fluent builder for
HttpJwtAuthorizer
.Properties to initialize HttpJwtAuthorizer.A builder forHttpJwtAuthorizerProps
An implementation forHttpJwtAuthorizerProps
Authorize Http Api routes via a lambda function.A fluent builder forHttpLambdaAuthorizer
.Properties to initialize HttpTokenAuthorizer.A builder forHttpLambdaAuthorizerProps
An implementation forHttpLambdaAuthorizerProps
Specifies the type responses the lambda returns.Authorize Http Api routes on whether the requester is registered as part of an AWS Cognito user pool.A fluent builder forHttpUserPoolAuthorizer
.Properties to initialize HttpUserPoolAuthorizer.A builder forHttpUserPoolAuthorizerProps
An implementation forHttpUserPoolAuthorizerProps
Authorize WebSocket API Routes with IAM.Authorize WebSocket Api routes via a lambda function.A fluent builder forWebSocketLambdaAuthorizer
.Properties to initialize WebSocketTokenAuthorizer.A builder forWebSocketLambdaAuthorizerProps
An implementation forWebSocketLambdaAuthorizerProps