Autenticación JWT en typescript, express

Implementación de Autenticación JWT en Express con TypeScript. Aprende a proteger tus APIs con JSON Web Tokens de forma efectiva y segura en tu aplicación Node.js.

22 nov 2025 • 3 min read • Q2BSTUDIO Team

Implementación de Autenticación JWT en Express con TypeScript

En este artículo explicamos cómo proteger rutas en Express usando TypeScript e implementación de tokens JWT para autenticar y autorizar usuarios.

Paso 1 Generación del token Al iniciar sesión se debe crear un token y entregarlo al cliente. La función jwt.sign toma tres parámetros principales payload que suele ser el id del usuario secret clave privada que defines en tu servidor y options configuraciones opcionales como expiresIn issuer audience y otros. Con jwt.sign se genera el token. Para que el cliente lo reenvíe al solicitar rutas protegidas lo más apropiado es almacenarlo en una cookie usando res.cookie nombre por ejemplo jwt value el token y opciones como maxAge secure httpOnly sameSite para mejorar la seguridad.

Paso 2 Middleware de protección Crear un middleware que lea el token desde las cookies y lo verifique con jwt.verify token y secret. La verificación reconstruye la firma a partir del header y del payload y la compara con la firma incluida en el token. Si la verificación falla se deniega el acceso. Además del verify conviene comprobar que el usuario aún exista y que el token no esté revocado o caducado.

Flujo de uso típico En un endpoint de registro o login primero validas credenciales y luego llamas a una función genToken que construye el payload y llama a jwt.sign. Guardas el token en una cookie segura y devuelves la respuesta con información mínima. En rutas protegidas el middleware verifica el token y añade los datos de usuario al objeto request para que los controladores puedan usarlos.

Buenas prácticas de seguridad Usar HTTPS para todas las comunicaciones, marcar cookies como secure y httpOnly, establecer sameSite estricto cuando sea posible, aplicar expiración razonable y usar refresh tokens para sesiones prolongadas. Considerar listas de revocación para tokens comprometidos, rotación periódica de claves y comprobación de algorítmos permitidos como HS256 o RS256 según la arquitectura.

Consideraciones específicas para TypeScript Definir tipos para el payload del token y extender la interfaz Request para incluir los datos del usuario evita errores en tiempo de compilación. Usar middlewares tipados facilita el mantenimiento y la lectura del código.

Ejemplo de flujo resumido 1 Validar credenciales 2 Generar token con jwt.sign 3 Guardar token en cookie con res.cookie 4 Proteger rutas con middleware que usa jwt.verify 5 Comprobar existencia del usuario y permisos antes de permitir la operación

Q2BSTUDIO Somos Q2BSTUDIO una empresa de desarrollo de software especializada en aplicaciones a medida y software a medida, con experiencia en inteligencia artificial, ciberseguridad y servicios cloud AWS y Azure. Diseñamos soluciones seguras y escalables que incluyen desde agentes IA hasta cuadros de mando con power bi y servicios de inteligencia de negocio. Si buscas desarrollar una aplicación robusta y segura visita nuestra página de desarrollo de aplicaciones y software a medida y conoce cómo podemos integrar ia para empresas y agentes IA en tus procesos con nuestra unidad de inteligencia artificial.

Palabras clave incluidas 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 implementar autenticación JWT segura en TypeScript y Express o para auditar la seguridad de tus aplicaciones contacta con Q2BSTUDIO y te asesoramos en arquitectura, implementación y mejores prácticas.

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