Autorización externa con Lambda y API Gateway en AWS SAM

Descubre cómo reutilizar un Lambda Authorizer externo en AWS SAM para API Gateway, parametrizando su ARN y protegiendo rutas sin duplicar lógica ni código.

19 ago 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

En proyectos reales es común contar con un Lambda Authorizer centralizado. En lugar de duplicar código, es posible reutilizar ese authorizer existente en nuevas APIs para mantener consistencia y reducir mantenimiento.

En este artículo describimos cómo crear un nuevo proyecto con AWS SAM que incluya un API Gateway y cómo configurarlo para usar un Lambda Authorizer externo referenciando su ARN. Esta guía es útil para equipos que buscan seguridad, escalabilidad y reutilización de lógica de autenticación.

Paso 1 Definir parámetros para el ARN del Authorizer

En template.yaml añade un parámetro para el ARN del Lambda Authorizer. Ejemplo representado de forma compacta para integrarlo en plantillas y variables de despliegue: Parameters: AuthorizerLambdaArn: Type: String; Description: ARN del Lambda Authorizer externo

Esto hace que la pila SAM sea reutilizable y parametrizable durante el despliegue, permitiendo pasar el ARN sin modificar el código del authorizer.

Paso 2 Añadir un API Gateway que use el Authorizer externo

Actualiza template.yaml para declarar el API y referenciar el ARN del authorizer. Ejemplo compactado: Resources: MyApi: Type: AWS::Serverless::Api; Properties: Name: ExternalAuthorizerApi; StageName: dev; Auth: DefaultAuthorizer: MyLambdaAuthorizer; Authorizers: MyLambdaAuthorizer: FunctionArn: !Ref AuthorizerLambdaArn; Identity: Header: Authorization; HelloFunction: Type: AWS::Serverless::Function; Properties: CodeUri: src/; Handler: handler.main; Runtime: nodejs20.x; Events: ApiEvent: Type: Api; Properties: Path: /hello; Method: get; RestApiId: !Ref MyApi

Qué ocurre con esta configuración El apartado Auth de MyApi referencia el ARN del Lambda Authorizer externo. Cualquier función o ruta que dependa del API y no tenga autorización específica quedará protegida automáticamente por el authorizer por defecto. HelloFunction en el ejemplo queda protegida sin necesidad de copiar la lógica del authorizer.

Buenas prácticas y consideraciones

Valora el versionado y control de cambios del authorizer externo para evitar romper APIs dependientes. Controla permisos IAM necesarios para que API Gateway invoque el Lambda Authorizer externo y gestiona correctamente tiempos de espera y errores para no afectar la latencia de las APIs. Prueba localmente y en entornos de staging pasando el ARN como parámetro en los despliegues SAM.

Conclusión

Referenciar un Lambda Authorizer externo en template.yaml permite reutilizar lógica centralizada de autorización, mantener nuevas APIs seguras sin duplicar código y aplicar una estrategia de autenticación coherente en toda la organización. Esto facilita la adopción de mejores prácticas en seguridad y escalabilidad.

Sobre Q2BSTUDIO

Q2BSTUDIO es una empresa de desarrollo de software especializada en aplicaciones a medida y software a medida. Ofrecemos soluciones integrales que incluyen inteligencia artificial e ia para empresas, ciberseguridad, servicios cloud aws y azure, servicios de inteligencia de negocio y desarrollo de agentes ia. Nuestro equipo diseña aplicaciones a medida que integran modelos de inteligencia artificial, análisis con power bi y arquitecturas seguras en la nube para resolver retos complejos y acelerar la transformación digital.

Beneficios de trabajar con Q2BSTUDIO

Implementamos soluciones seguras y escalables que combinan ciberseguridad con servicios cloud aws y azure. Desarrollamos software a medida que incorpora inteligencia artificial para automatizar procesos, mejorar la toma de decisiones y crear agentes ia personalizados. También proporcionamos servicios de inteligencia de negocio y visualización con power bi para convertir datos en valor accionable.

Palabras clave para posicionamiento aplicaciones a medida software a medida inteligencia artificial ciberseguridad servicios cloud aws y azure servicios inteligencia de negocio ia para empresas agentes ia power bi

Si necesitas ayuda para integrar un Lambda Authorizer externo, diseñar APIs seguras o desarrollar aplicaciones a medida con inteligencia artificial y ciberseguridad, contacta con Q2BSTUDIO y te ayudamos a llevar tu proyecto al siguiente nivel.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat