Saltar al contenido

Autorizador de grupos de usuarios de AWS CDK

Hola, descubrimos la respuesta a lo que buscas, deslízate y la obtendrás más abajo.

Solución:

A partir de September 2019 La respuesta de @bgdnip no se traduce exactamente para typescript. Lo tengo funcionando con lo siguiente:

const api = new RestApi(this, 'RestAPI', 
    restApiName: 'Rest-Name',
    description: 'API for journey services.',
);

const putIntegration = new LambdaIntegration(handler);

const auth = new CfnAuthorizer(this, 'APIGatewayAuthorizer', 
    name: 'customer-authorizer',
    identitySource: 'method.request.header.Authorization',
    providerArns: [providerArn.valueAsString],
    restApiId: api.restApiId,
    type: AuthorizationType.COGNITO,
);

const post = api.root.addMethod('PUT', putIntegration,  authorizationType: AuthorizationType.COGNITO );
const postMethod = post.node.defaultChild as CfnMethod;
postMethod.addOverride('Properties.AuthorizerId',  Ref: auth.logicalId );

Esto es de https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html#cfn_layer_resource_props

ACTUALIZAR Octubre

Lo anterior ya está desactualizado e innecesario y se puede lograr con lo siguiente con aws-cdk 1.12.0

const api = new RestApi(this, 'RestAPI', 
    restApiName: 'Rest-Name',
    description: 'API for journey services.',
);

const putIntegration = new LambdaIntegration(handler);

const auth = new CfnAuthorizer(this, 'APIGatewayAuthorizer', 
    name: 'customer-authorizer',
    identitySource: 'method.request.header.Authorization',
    providerArns: [providerArn.valueAsString],
    restApiId: api.restApiId,
    type: AuthorizationType.COGNITO,
);

const post = api.root.addMethod('PUT', putIntegration, 
    authorizationType: AuthorizationType.COGNITO,
    authorizer:  authorizerId: auth.ref 
);

Esta es mi solución en TypeScript (basada algo en la respuesta de bgdnlp)

import  App, Stack, Aws  from '@aws-cdk/core';
import  Code, Function, Runtime  from '@aws-cdk/aws-lambda';
import  LambdaIntegration, RestApi, CfnAuthorizer, CfnMethod  from '@aws-cdk/aws-apigateway';

const app = new App();
const stack = new Stack(app, `mystack`);
const api = new RestApi(stack, `myapi`);

const region = Aws.REGION;
const account = Aws.ACCOUNT_ID;
const cognitoArn = `arn:aws:cognito-idp:$region:$account:userpool/$USER_POOL_ID`;

const authorizer = new CfnAuthorizer(stack, 'Authorizer', 
  name: `myauthorizer`,
  restApiId: api.restApiId,
  type: 'COGNITO_USER_POOLS',
  identitySource: 'method.request.header.Authorization',
  providerArns: [cognitoArn],
);

const lambda = new Function(stack, 'mylambda', 
  runtime: Runtime.NODEJS_10_X,
  code: Code.asset('dist'),
  handler: `index.handler`,
);

const integration = new LambdaIntegration(lambda);

const res = api.root.addResource('hello');

const method = res.addMethod('GET', integration);

const child = method.node.findChild('Resource') as CfnMethod;

child.addPropertyOverride('AuthorizationType', 'COGNITO_USER_POOLS');

child.addPropertyOverride('AuthorizerId',  Ref: authorizer.logicalId );

Las respuestas anteriores ya no funcionan porque el authorizerId la propiedad fue reemplazada con authorizer, que no está completamente implementado en este momento.

En su lugar, se puede hacer utilizando los objetos CfnResource subyacentes, como se describe en la guía oficial.

Aquí está el código de Python como ejemplo:

from aws_cdk import cdk
from aws_cdk import aws_apigateway


class Stk(cdk.Stack):
    def __init__(self, app, id):
        super().__init__(app, id)

        api_gw = aws_apigateway.RestApi(self, 'MyApp')
        post_method = api_gw.root.add_method(http_method='POST')

        # Create authorizer using low level CfnResource
        api_gw_authorizer = aws_apigateway.CfnAuthorizer(
            scope=self,
            id='my_authorizer',
            rest_api_id=api_gw.rest_api_id,
            name='MyAuth',
            type='COGNITO_USER_POOLS',
            identity_source='method.request.header.name.Authorization',
            provider_arns=[
                'arn:aws:cognito-idp:eu-west-1:123456789012:userpool/'
                'eu-west-1_MyCognito'])

        # Get underlying post_method Resource object. Returns CfnMethod
        post_method_resource = post_method.node.find_child('Resource')
        # Add properties to low level resource
        post_method_resource.add_property_override('AuthorizationType',
                                                   'COGNITO_USER_POOLS')
        # AuthorizedId uses Ref, simulate with a dictionaty
        post_method_resource.add_property_override(
                'AuthorizerId',
                "Ref": api_gw_authorizer.logical_id)


app = cdk.App()
stk = Stk(app, "myStack")

app.synth()

Más adelante puedes encontrar las aclaraciones de otros desarrolladores, tú aún tienes la libertad de mostrar el tuyo si lo crees conveniente.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *