Skip to main content

Authorizers for AWS APIGateway V2

Project description

AWS APIGatewayv2 Authorizers

---

cdk-constructs: Experimental

The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.


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.

from aws_cdk.aws_apigatewayv2_authorizers_alpha 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"]
)

Route Authorization

Authorization can also 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 and GET /books/{id} use the default authorizer settings on the api
  • POST /books will require the [write:books] scope
  • POST /login removes the default authorizer (unauthenticated route)
from aws_cdk.aws_apigatewayv2_authorizers_alpha import HttpJwtAuthorizer
from aws_cdk.aws_apigatewayv2_integrations_alpha 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()
)

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 fails
  • 403 - Forbidden - When the JWT validation is successful but the required scopes are not met
from aws_cdk.aws_apigatewayv2_authorizers_alpha import HttpJwtAuthorizer
from aws_cdk.aws_apigatewayv2_integrations_alpha 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
)

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 aws_cdk.aws_cognito as cognito
from aws_cdk.aws_apigatewayv2_authorizers_alpha import HttpUserPoolAuthorizer
from aws_cdk.aws_apigatewayv2_integrations_alpha 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
)

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.

from aws_cdk.aws_apigatewayv2_authorizers_alpha import HttpLambdaAuthorizer, HttpLambdaResponseType
from aws_cdk.aws_apigatewayv2_integrations_alpha import HttpUrlIntegration

# 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
)

IAM Authorizers

API Gateway supports IAM via the included HttpIamAuthorizer and grant syntax:

from aws_cdk.aws_apigatewayv2_authorizers_alpha import HttpIamAuthorizer
from aws_cdk.aws_apigatewayv2_integrations_alpha 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)

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.

from aws_cdk.aws_apigatewayv2_authorizers_alpha import WebSocketLambdaAuthorizer
from aws_cdk.aws_apigatewayv2_integrations_alpha 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
    )
)

IAM Authorizer

IAM authorizers can be used to allow identity-based access to your WebSocket API.

from aws_cdk.aws_apigatewayv2_authorizers_alpha import WebSocketIamAuthorizer
from aws_cdk.aws_apigatewayv2_integrations_alpha 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]
        )
    ]
))

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Built Distribution

File details

Details for the file aws-cdk.aws-apigatewayv2-authorizers-alpha-2.89.0a0.tar.gz.

File metadata

File hashes

Hashes for aws-cdk.aws-apigatewayv2-authorizers-alpha-2.89.0a0.tar.gz
Algorithm Hash digest
SHA256 efa23f021efdca83f037569d41d7e96023c3750417fc976023688397f7f57715
MD5 f7cd14bb47227be3c82780182f67f5d2
BLAKE2b-256 9d9bdbac4be0a875fa01bd7103dfd28bcc551a275f1e0a472d2480c265c91fbd

See more details on using hashes here.

File details

Details for the file aws_cdk.aws_apigatewayv2_authorizers_alpha-2.89.0a0-py3-none-any.whl.

File metadata

File hashes

Hashes for aws_cdk.aws_apigatewayv2_authorizers_alpha-2.89.0a0-py3-none-any.whl
Algorithm Hash digest
SHA256 7b56ea2889e8a340bfd4feb67f0798827bf58090d368763a59cd0223fe2dd916
MD5 752c573d59b8b4d861c372bb169659e4
BLAKE2b-256 24552d0930cbc1214aeebde9473efdedfad8ca6ce12767ea32c44ec8c85d76b1

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page