Protege Tu Aplicación Next.js Con una Política de Seguridad de Contenido

Rate this content
Bookmark
Github

Aprende por qué deberías preocuparte por la Política de Seguridad de Contenido (CSP) y cómo implementarla en una aplicación Next.JS para mejorar tu capa de seguridad. Comprende los conceptos básicos de CSP, las directivas y su papel en la prevención de ataques web. Avanzando hacia Next.js, la sesión profundizará en los detalles de implementación, cubriendo los hashes "nounce" para scripts en línea usando middlewares y las trampas de estrategias comunes. Al final de la sesión, los participantes estarán equipados con el conocimiento y las habilidades para implementar y evaluar una política CSP robusta en Next.js, aprovechando sus últimas características de la versión 13, protegiendo eficazmente sus aplicaciones web contra ataques en línea.

Lucas Estevão
Lucas Estevão
6 min
23 Oct, 2023

Video Summary and Transcription

Lucas Esteveau discute la importancia de la Política de Seguridad de Contenido (CSP) como una capa adicional de seguridad para los navegadores. Explica cómo validar e implementar CSP utilizando herramientas como csp-evaluator.withgoogle.com y observatory.mozilla.org. También destaca el uso de componentes de servidor y middleware en el proyecto Hudafor para establecer y hacer cumplir las directivas CSP. Lucas aconseja comenzar con un CSP solo de informe, revisar los resultados y aplicar gradualmente la política. Enfatiza la importancia de revisar los informes de violación de políticas e iterar el proceso al hacer cambios.

Available in English

1. Introducción a la Política de Seguridad de Contenido

Short description:

Soy Lucas Esteveau, un contratista principal de ingeniería de interfaz de usuario de Avenue Code en Apple. Hablemos de por qué deberías preocuparte por una Política de Seguridad de Contenido. Los navegadores tienen características de seguridad, pero no pueden prevenir todos los ataques. Una CSP es una capa de seguridad que restringe la funcionalidad del navegador. Puedes implementarla usando etiquetas meta o encabezados. En Next.js, puedes agregar directivas en tu archivo de configuración de next.

Hola a todos. Gracias por tenerme en la Conferencia React Advanced 2023. Soy Lucas Esteveau. Soy un contratista principal de ingeniería de interfaz de usuario de Avenue Code en Apple desde que me mudé a California hace unos cuatro años. También presento un podcast en portugués brasileño sobre la carrera en tecnología. Así que si tienes curiosidad y hablas portugués, échale un vistazo en las principales plataformas de streaming.

Estoy realmente emocionado de hablarles sobre cómo debería ser su aplicación Next.js con una Política de Seguridad de Contenido hoy y quiero empezar respondiendo ¿por qué debería preocuparme por una Política de Seguridad de Contenido? Bueno, resulta que tu navegador no es 100% seguro. Ya sea React o Next.js o cualquier biblioteca o marco que puedas estar utilizando para tu aplicación web. Aunque los navegadores tienen características de seguridad incorporadas como la política de origen único y CORS y bibliotecas y marcos como React y Next.js hacen un trabajo bastante decente en la limpieza del código y proporcionando características web para cerrar brechas de seguridad, no podemos darlo por hecho. Si un código como este se inyecta en tu sitio web, tu navegador o las características predeterminadas de React no pueden prevenir que esto se ejecute. Es decir, tu aplicación podría estar expuesta a ataques de scripting de tipo cruzado, y los preciados datos podrían filtrarse.

Ahí es cuando una CSP resulta útil. Una política de seguridad de contenido. Es una capa de seguridad que ayuda a proteger las aplicaciones de ataques como los ataques de scripting de tipo cruzado o ataques de inyección de datos, y lo hace restringiendo la funcionalidad del navegador. Una política de seguridad de contenido está compuesta por una lista de directivas de política. El navegador estará limitado a permitir solo lo que definas en tu política. Así que aquí tienes un ejemplo de cómo se compone una política de seguridad de contenido. Aquí otro ejemplo, donde las directivas de política, donde estoy definiendo que las fuentes predeterminadas de contenido, déjame volver a este. Aquí hay ejemplos de directivas de política donde estoy definiendo que las fuentes predeterminadas de contenido deben provenir de mi dominio. Y estoy añadiendo una excepción para las fuentes, porque quiero permitir que se descarguen las Fuentes Web de Google.

Hay dos formas de implementar una política de seguridad de contenido en tu aplicación. La primera es añadiendo una etiqueta meta en el encabezado HTML, pero esta no es la preferida. La otra forma, y la mejor manera de hacerlo, es crear un encabezado para ello. Así que aquí estamos añadiendo una clave CSP y el valor que contendrá nuestras directivas. En este caso, como dije antes, estoy diciendo que la fuente predeterminada de mi contenido, va a venir de mi dominio, y añadiendo una excepción para las fuentes que también pueden venir de Google. Cuando se trata de Next.js, así es como se ve una CSP. Simplemente puedes añadir una lista de directivas en tu encabezado dentro de tu archivo de configuración de next. Puedes definir a qué tipo de solicitudes se aplicará la CSP utilizando el atributo de origen. En este caso, estoy diciendo que mi política de seguridad de contenido se aplicará a cada una de las solicitudes. No estoy filtrando, aunque podrías hacerlo, filtrando tu API por ejemplo.

2. Validación e Implementación de CSP

Short description:

Para validar tu CSP, puedes usar csp-evaluator.withgoogle.com o observatory.mozilla.org. Announced permite ejecutar scripts en línea de forma segura. Los componentes del servidor obtienen el announce del encabezado. Un middleware en el proyecto Hudafor establece el announce en el encabezado de la solicitud. El middleware define directivas y establece el encabezado de solicitud de CSP. Aplica directivas dinámicamente en función del entorno. Comienza con CSP solo de informe, revisa los resultados y aplica la política más tarde. El navegador envía un informe con una solicitud POST al punto final definido. Revisa el informe para detectar violaciones de políticas. Repite el proceso al hacer cambios. Encuentra la aplicación de muestra Next.js con CSP en mi GitHub.

¿Qué pasa con la validation? Es bastante simple. Tienes prácticamente dos recursos que puedes usar para validar tu CSP. Puedes comprobarlo yendo a csp-evaluator.withgoogle.com o a observatory.mozilla.org. Asegúrate de que todo se ve bien, estás siguiendo las mejores prácticas y mueve el código a tu propia aplicación.

Habrá casos en los que necesites scripts en línea. Para esos escenarios, announced permitirá que tus scripts se ejecuten sin perder la security de tu CSP. Announced es básicamente una cadena aleatoria, un hash creado para un solo uso. Veamos cómo se puede usar announced en un componente de servidor. Con una política de CSP estricta establecida, los navegadores modernos solo ejecutarán scripts cuyo atributo announced coincida con el valor establecido en el encabezado de la política. Los scripts añadidos dinámicamente a la página por scripts con el announce adecuado también serán ejecutados.

Así es como se ve un componente de servidor, como dije, obteniendo el announce del encabezado. Para exponer el announce, necesitamos crear un middleware en el proyecto Hudafor y establecer el announce en el encabezado de la solicitud. Aquí lo estamos haciendo con la ayuda de crypto. Para usar el announce en nuestra política, podemos definir las directivas y establecer el encabezado de solicitud de CSP dentro de nuestro middleware. Incluso podemos aplicar directivas dinámicamente dependiendo del entorno en el que nos encontramos. Aquí estoy comprobando si no estoy en producción y si no lo estoy, puedo perder mi CSP security ya que estoy en modo de desarrollo. Así es como se ve nuestro middleware. Sé que parece mucho, pero no te preocupes por cada línea de código. La idea aquí es que entiendas el proceso. Puedes revisar mi código en mi GitHub.

Pero revisémoslo. Primero creamos el announce, luego definimos nuestro CSP y añadimos ambos a los encabezados de la solicitud. No necesitas aplicar todas las reglas a la vez y arriesgarte a romper tu aplicación. Puedes añadir primero el CSP solo de informe, revelar los resultados y aplicarlo más tarde. Así es como se ve un CSP solo de informe, muy similar al regular. El navegador enviará una solicitud HTTP POST al punto final que definamos, con un informe que se ve así. Puedes ver la política original y revisar lo que está rompiendo. Y luego puedes repetir este proceso cuando hagas cambios en tu política. Solo de informe, revelar y aplicar. Gracias. Espero que hayas encontrado útil este contenido. Puedes encontrar la aplicación de muestra de Next.js con una CSP implementada en mi GitHub. ¡Y feliz codificación!

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Building Better Websites with Remix
React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
Top Content
Remix is a new web framework from the creators of React Router that helps you build better, faster websites through a solid understanding of web fundamentals. Remix takes care of the heavy lifting like server rendering, code splitting, prefetching, and navigation and leaves you with the fun part: building something awesome!
Speeding Up Your React App With Less JavaScript
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
Full Stack Documentation
JSNation 2022JSNation 2022
28 min
Full Stack Documentation
Top Content
Interactive web-based tutorials have become a staple of front end frameworks, and it's easy to see why — developers love being able to try out new tools without the hassle of installing packages or cloning repos.But in the age of full stack meta-frameworks like Next, Remix and SvelteKit, these tutorials only go so far. In this talk, we'll look at how we on the Svelte team are using cutting edge web technology to rethink how we teach each other the tools of our trade.
Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Concurrent React and Server Components are changing the way we think about routing, rendering, and fetching in web applications. Next.js recently shared part of its vision to help developers adopt these new React features and take advantage of the benefits they unlock.In this talk, we’ll explore the past, present and future of routing in front-end applications and discuss how new features in React and Next.js can help us architect more performant and feature-rich applications.
From GraphQL Zero to GraphQL Hero with RedwoodJS
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
We all love GraphQL, but it can be daunting to get a server up and running and keep your code organized, maintainable, and testable over the long term. No more! Come watch as I go from an empty directory to a fully fledged GraphQL API in minutes flat. Plus, see how easy it is to use and create directives to clean up your code even more. You're gonna love GraphQL even more once you make things Redwood Easy!
SolidJS: Why All the Suspense?
JSNation 2023JSNation 2023
28 min
SolidJS: Why All the Suspense?
Top Content
Solid caught the eye of the frontend community by re-popularizing reactive programming with its compelling use of Signals to render without re-renders. We've seen them adopted in the past year in everything from Preact to Angular. Signals offer a powerful set of primitives that ensure that your UI is in sync with your state independent of components. A universal language for the frontend user interface.
But what about Async? How do we manage to orchestrate data loading and mutation, server rendering, and streaming? Ryan Carniato, creator of SolidJS, takes a look at a different primitive. One that is often misunderstood but is as powerful in its use. Join him as he shows what all the Suspense is about.

Workshops on related topic

Building WebApps That Light Up the Internet with QwikCity
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Miško Hevery
Miško Hevery
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
Back to the Roots With Remix
React Summit 2023React Summit 2023
106 min
Back to the Roots With Remix
Featured Workshop
Alex Korzhikov
Pavlik Kiselev
2 authors
The modern web would be different without rich client-side applications supported by powerful frameworks: React, Angular, Vue, Lit, and many others. These frameworks rely on client-side JavaScript, which is their core. However, there are other approaches to rendering. One of them (quite old, by the way) is server-side rendering entirely without JavaScript. Let's find out if this is a good idea and how Remix can help us with it?
Prerequisites- Good understanding of JavaScript or TypeScript- It would help to have experience with React, Redux, Node.js and writing FrontEnd and BackEnd applications- Preinstall Node.js, npm- We prefer to use VSCode, but also cloud IDEs such as codesandbox (other IDEs are also ok)
Build a Headless WordPress App with Next.js and WPGraphQL
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
Kellen Mace
Kellen Mace
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.
Next.js 13: Data Fetching Strategies
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
Alice De Mauro
Alice De Mauro
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
0 to Auth in an hour with ReactJS
React Summit 2023React Summit 2023
56 min
0 to Auth in an hour with ReactJS
WorkshopFree
Kevin Gao
Kevin Gao
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool. There are multiple alternatives that are much better than passwords to identify and authenticate your users - including SSO, SAML, OAuth, Magic Links, One-Time Passwords, and Authenticator Apps.
While addressing security aspects and avoiding common pitfalls, we will enhance a full-stack JS application (Node.js backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session securely for subsequent client requests, validating / refreshing sessions- Basic Authorization - extracting and validating claims from the session token JWT and handling authorization in backend flows
At the end of the workshop, we will also touch other approaches of authentication implementation with Descope - using frontend or backend SDKs.
Create a Visually Editable Next.js Website Using React Bricks, With Blog and E-commerce
React Summit 2023React Summit 2023
139 min
Create a Visually Editable Next.js Website Using React Bricks, With Blog and E-commerce
WorkshopFree
Matteo Frana
Matteo Frana
- React Bricks: why we built it, what it is and how it works- Create a free account- Create a new project with Next.js and Tailwind- Explore the directory structure- Anatomy of a Brick- Create a new Brick (Text-Image)- Add a title and description with RichText visual editing- Add an Image with visual editing- Add Sidebar controls to edit props (padding and image side)- Nesting Bricks using the Repeater component- Create an Image gallery brick- Publish on Netlify or Vercel- Page Types and Custom fields- Access Page meta values- Internationalization- How to reuse content across pages: Stories and Embeds- How to create an E-commerce with Products’ data from an external database and landing pages created visually in React Bricks- Advanced enterprise features: flexible permissions, locked structure, custom visual components