Auth0 y Vue: Una Combinación Perfecta para el Desarrollo de Aplicaciones Seguras

Rate this content
Bookmark
Tyler Clark
Tyler Clark
9 min
15 May, 2023

Video Summary and Transcription

Hola Vue.js live. Mi nombre es Tyler Clark y hoy daré una charla titulada, Vue.js: Construyendo aplicaciones seguras. Discutiré las mayores amenazas de las aplicaciones hoy en día, incluyendo ataques de fuerza bruta, relleno de credenciales y phishing. También presentaré soluciones como WebAuthn para autenticación sin contraseña utilizando biometría. Como pueden ver aquí, usen la función credentials.create para obtener un desafío de una solicitud al servidor. Luego, pasen la información necesaria sobre el usuario y los tipos de clave pública aceptables al servidor. WebAuthn elimina los flujos basados en contraseñas, creando un par de claves privadas y públicas seguras.

Available in English

1. Introducción a Vue.js y Seguridad de Aplicaciones

Short description:

Hola Vue.js en vivo. Mi nombre es Tyler Clark y hoy daré una charla titulada, Vue.js: Construyendo aplicaciones seguras. Soy un defensor del desarrollo de personal en Auth0 de Okta con nueve años de experiencia en el campo de la tecnología. Discutiré las mayores amenazas de aplicaciones hoy en día, incluyendo ataques de fuerza bruta, relleno de credenciales y phishing. También presentaré soluciones como WebAuthn para la autenticación sin contraseña utilizando biometría.

Hola Vue.js en vivo. En primer lugar, gracias por tenerme aquí. Me alegra estar aquí y hablar con todos ustedes hoy.

Mi nombre es Tyler Clark y hoy daré una charla titulada, Vue.js: Construyendo aplicaciones seguras. Un breve resumen sobre mí, mi nombre es Tyler Clark nuevamente. Soy un defensor del desarrollo de personal en Auth0 de Okta. He trabajado en el campo de la tecnología durante unos nueve años, principalmente en JavaScript, principalmente en el front-end y back-end, pero he hecho un poco de todo para pequeñas empresas hasta empresas de nivel enterprise. Puedes encontrarme en dos lugares, Twitter en I Am Tyler W Clark, también puedes encontrarme en Edcad.io, tengo varios cursos allí, y estaré en el Discord de la conferencia , así que por favor encuéntrame allí y hazme cualquier tipo de preguntas de seguimiento porque estoy seguro de que tendrás algunas al final de esta charla.

Muy bien, esta es una charla rápida, solo tengo unos siete minutos, así que vamos directo al grano. Seguridad es, bueno, no es algo fácil de hablar, especialmente en un período de tiempo de siete minutos, pero haremos nuestro mejor esfuerzo hoy. Quiero hablar sobre algunas de las mayores amenazas de aplicaciones hoy en día que vemos en muchas de estas brechas que ocurren. Tengo un par de soluciones que puedes agregar y aplicar a través de una aplicación Vue, y al final voy a dar algunos enlaces para profundizar un poco más en esto.

Ahora las tres amenazas de seguridad más comunes en las aplicaciones hoy en día son los ataques de fuerza bruta, el relleno de credenciales y el phishing. Los ataques de fuerza bruta básicamente son una cantidad excesiva de intentos y errores que los hackers utilizan para tratar de adivinar tu contraseña. El relleno de credenciales es cuando has utilizado el mismo identificador de correo electrónico o nombre de usuario y contraseña en un sitio, ese sitio sufre una brecha y luego los hackers toman esa información y tratan de acceder a otras aplicaciones que esos usuarios podrían haber utilizado con las mismas combinaciones y tratan de obtener acceso a ellas. Y el phishing es cuando recibes un correo electrónico que parece ser de Amazon, haces clic en el enlace, parece ser una página de inicio de sesión de Amazon, le das tu nombre de usuario y contraseña, y resulta que no es Amazon y acabas de entregar tu nombre de usuario y contraseña.

Mira, las contraseñas son terribles, todos las odian, por eso cosas como 1Password y estos administradores de contraseñas son tan populares porque es una solución integral, se rellena automáticamente, pero es una lástima que todavía tengamos que usarlas hoy en día. Entonces, ¿cuáles son nuestras opciones hoy como desarrolladores en nuestras aplicaciones Vue? Hay tres que quiero mencionar aquí, pero hoy compartiré el código de esta primera opción, WebAuthn, que utiliza biometría como tu huella digital o tu iris para iniciar sesión en una aplicación. Otra opción común es enviar un correo electrónico o un mensaje de texto que contenga una contraseña de un solo uso que los usuarios luego pueden ingresar en tu pantalla de inicio de sesión que automáticamente inicia sesión en los usuarios. Ambas opciones inician sesión automáticamente sin necesidad de una contraseña, por lo que no hay riesgo de que sea vulnerada.

Entonces, ¿qué es WebAuthn? WebAuthn es una abreviatura de la API de Autenticación Web. Está integrado en plataformas como el navegador. Autenticarse con WebAuthn basado en biometría es equivalente a la autenticación multifactor. Básicamente significa que cuando te autenticas una vez, como puedes ver en la diapositiva aquí, no se necesita una autenticación multifactor adicional. La autenticación multifactor significa que alguien usa una contraseña para iniciar sesión y luego también necesita proporcionar un texto y un código para ingresar. La autenticación requiere múltiples factores para ingresar, pero si usas WebAuthn, eso cuenta para ambos. La autenticación sin contraseña basada en WebAuthn es inatacable, de lo que hablé en esa otra diapositiva. Ahora dije que está integrado en plataformas como Chrome, por lo que no es necesario usar alguna solución de identidad como Auth0 para poder usar esto en tu aplicación hoy en día. Está integrado en Chrome. Se utiliza el objeto Navigator.

2. Registro y Autenticación de WebAuthn

Short description:

Como puedes ver aquí, utiliza la función credentials.create para obtener un desafío de una solicitud al servidor. Luego, pasa la información necesaria sobre el usuario y los tipos de clave pública aceptables al servidor. Después de que el usuario complete el registro, puede iniciar sesión y volver a autenticarse proporcionando una afirmación generada por el método .credentials.get del objeto navigator.

Como puedes ver aquí, utiliza la función credentials.create pasando un código, que te mostraré aquí en un momento. Y podrías estar pensando, ¿cuál es el soporte en esto? Como usar Safari. Tienes usuarios en Edge o Internet Explorer. Aquí tienes un vistazo rápido al soporte del navegador para WebAuthn.

Muy bien, vamos directo al código aquí porque se me está acabando el tiempo. Digamos que tenemos dos botones aquí. Tenemos un botón de registro y un botón de inicio de sesión que estamos usando en nuestro componente. Tiene una función de registro e inicio de sesión.

Primero, hablemos sobre la función de registro. De inmediato, verás que estamos obteniendo un desafío de una solicitud al servidor aquí. Esta es una solicitud al servidor que nosotros controlamos. Un desafío es básicamente solo bytes generados aleatoriamente. Se utiliza para prevenir ataques de reproducción. Esto aquí, este await navigator es de lo que acabo de hablar. Esto está integrado en el navegador, está en el objeto window. Y este es el objeto navigator que proporciona este credentials.create. Verás que dentro de aquí le pasamos un objeto y hay un RP aquí, básicamente significa parte responsable. Este es el responsable de registrar y autenticar a este usuario en particular que está tratando de crear una cuenta. Dado ese usuario, este objeto de usuario será la información sobre el usuario que está registrándose actualmente.

Verás que hay un nombre, hay un ID y hay un nombre de visualización. Y la última pieza requerida en este objeto es pubkey cred params. Dentro de esto verás que es una matriz de objetos que describe qué tipos de clave pública son aceptables para el servidor. Y luego dentro de eso verás un tipo de clave pública y hay un ALG negativo siete. Ese número define qué tipo de algoritmo de firma se utilizará para crear esto. Y luego después de eso hacemos una publicación en la misma ruta, pero esto es una publicación proporcionando la respuesta devuelta por esta credencial.

Ahora, después de que un usuario haya completado el registro de su cuenta, se hayan ido, hayan vuelto y estén listos para iniciar sesión y volver a autenticarse. Durante esta autenticación, el usuario necesita demostrar que es dueño de la clave privada que registraron inicialmente. Lo harán proporcionando una afirmación. Y esto se genera haciendo .credentials.get en el objeto navigator. Esto recuperará la credencial generada durante el registro con la firma incluida.

3. Desafío WebAuthn y Pares de Claves

Short description:

Este desafío es similar al registro, generado en el servidor. La matriz 'allow credentials' le indica al navegador con qué credenciales autenticar. WebAuthn elimina los flujos basados en contraseñas, creando un par de claves privada y pública seguras. Consulta los enlaces para obtener más información sobre los pares de claves, el soporte del navegador y el SDK de vista de Auth0.

Este desafío aquí es muy similar al registro, proviene de un servidor. Se genera en el servidor, es un conjunto de bytes aleatorios. Y luego, lo último aquí es esta matriz para 'allow credentials'. Esto básicamente le indica al navegador con qué credenciales el servidor desea que el usuario se autentique. Por lo tanto, se pasa el ID de credencial recuperado y guardado durante el registro. Con esta información, luego hacemos una publicación en una ruta que poseemos con esto y el acompañante con la respuesta del navegador.

Muy bien, sé que acabo de decir mucho y gran parte de ese código puede haber pasado por encima de tu cabeza, pero lo que realmente quiero que entiendas es que en un flujo de registro o inicio de sesión basado en contraseñas que tenemos hoy en día, las contraseñas se envían a través de la web a un servidor y se almacenan en la base de datos de esa aplicación. Pero con WebAuthn, con la ayuda de una plataforma como un navegador, creamos un par de claves privada y pública. Esto contiene identificadores para el usuario y la organización, no hay contraseñas involucradas y no se almacenan contraseñas.

Por favor, consulta algunos de estos enlaces aquí para obtener más información sobre cómo funcionan los pares de claves privada y pública, por qué son más seguros y por qué han existido durante tanto tiempo. Ese enlace al soporte del navegador para ver si tu navegador está incluido. También hay un SDK de vista de Auth0 que puedes consultar. Esto te ayudará a instalar WebAuthn rápidamente y utilizar muchos otros factores diferentes. Si deseas profundizar más en WebAuthn y ver parte del código que puedes usar en tu aplicación hoy en día, también consulta ese enlace. Muchas gracias.

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

Everything Beyond State Management in Stores with Pinia
Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
When we think about Vuex, Pinia, or stores in general we often think about state management and the Flux patterns but not only do stores not always follow the Flux pattern, there is so much more about stores that make them worth using! Plugins, Devtools, server-side rendering, TypeScript integrations... Let's dive into everything beyond state management with Pinia with practical examples about plugins and Devtools to get the most out of your stores.
Welcome to Nuxt 3
Vue.js London Live 2021Vue.js London Live 2021
29 min
Welcome to Nuxt 3
Top Content
Explain about NuxtJS codebase refactor and challenges facing to implement Vue 3, Vite and other packages.
One Year Into Vue 3
Vue.js London Live 2021Vue.js London Live 2021
20 min
One Year Into Vue 3
Top Content
Vue 3 may still sound new to many users, but it's actually been released for over a year already. How did Vue 3 evolve during this period? Why did it take so long for the ecosystem to catch up? What did we learn from this process? What's coming next? We will discuss these questions in this talk!
Utilising Rust from Vue with WebAssembly
Vue.js London Live 2021Vue.js London Live 2021
8 min
Utilising Rust from Vue with WebAssembly
Top Content
Rust is a new language for writing high-performance code, that can be compiled to WebAssembly, and run within the browser. In this talk you will be taken through how you can integrate Rust, within a Vue application, in a way that's painless and easy. With examples on how to interact with Rust from JavaScript, and some of the gotchas to be aware of.
Vue: Feature Updates
Vue.js London 2023Vue.js London 2023
44 min
Vue: Feature Updates
Top Content
The creator of Vue js gives an update on the new features of the technology.
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
How many times did you implement the same flow in your application: check, if data is already fetched from the server, if yes - render the data, if not - fetch this data and then render it? I think I've done it more than ten times myself and I've seen the question about this flow more than fifty times. Unfortunately, our go-to state management library, Vuex, doesn't provide any solution for this.For GraphQL-based application, there was an alternative to use Apollo client that provided tools for working with the cache. But what if you use REST? Luckily, now we have a Vue alternative to a react-query library that provides a nice solution for working with server cache. In this talk, I will explain the distinction between local application state and local server cache and do some live coding to show how to work with the latter.

Workshops on related topic

Vue3: Modern Frontend App Development
Vue.js London Live 2021Vue.js London Live 2021
169 min
Vue3: Modern Frontend App Development
Top Content
Featured WorkshopFree
Mikhail Kuznetcov
Mikhail Kuznetcov
The Vue3 has been released in mid-2020. Besides many improvements and optimizations, the main feature of Vue3 brings is the Composition API – a new way to write and reuse reactive code. Let's learn more about how to use Composition API efficiently.

Besides core Vue3 features we'll explain examples of how to use popular libraries with Vue3.

Table of contents:
- Introduction to Vue3
- Composition API
- Core libraries
- Vue3 ecosystem

Prerequisites:
IDE of choice (Inellij or VSC) installed
Nodejs + NPM
Using Nitro – Building an App with the Latest Nuxt Rendering Engine
Vue.js London Live 2021Vue.js London Live 2021
117 min
Using Nitro – Building an App with the Latest Nuxt Rendering Engine
Top Content
Workshop
Daniel Roe
Daniel Roe
We'll build a Nuxt project together from scratch using Nitro, the new Nuxt rendering engine, and Nuxt Bridge. We'll explore some of the ways that you can use and deploy Nitro, whilst building a application together with some of the real-world constraints you'd face when deploying an app for your enterprise. Along the way, fire your questions at me and I'll do my best to answer them.
Going on an adventure with Nuxt 3, Motion UI and Azure
JSNation 2022JSNation 2022
141 min
Going on an adventure with Nuxt 3, Motion UI and Azure
WorkshopFree
Melanie de Leeuw
Melanie de Leeuw
We love easily created and deployed web applications! So, let’s see what a very current tech stack like Nuxt 3, Motion UI and Azure Static Web Apps can do for us. It could very well be a golden trio in modern day web development. Or it could be a fire pit of bugs and errors. Either way it will be a learning adventure for us all. Nuxt 3 has been released just a few months ago, and we cannot wait any longer to explore its new features like its acceptance of Vue 3 and the Nitro Engine. We add a bit of pizzazz to our application with the Sass library Motion UI, because static design is out, and animations are in again.Our driving power of the stack will be Azure. Azure static web apps are new, close to production and a nifty and quick way for developers to deploy their websites. So of course, we must try this out.With some sprinkled Azure Functions on top, we will explore what web development in 2022 can do.
TresJS create 3D experiences declaratively with Vue Components
Vue.js London 2023Vue.js London 2023
137 min
TresJS create 3D experiences declaratively with Vue Components
Workshop
Alvaro Saburido
Alvaro Saburido
- Intro 3D - Intro WebGL- ThreeJS- Why TresJS- Installation or Stackblitz setup - Core Basics- Setting up the Canvas- Scene- Camera- Adding an object- Geometries- Arguments- Props- Slots- The Loop- UseRenderLoop composable- Before and After rendering callbacks- Basic Animations- Materials- Basic Material- Normal Material- Toon Material- Lambert Material- Standard and Physical Material- Metalness, roughness - Lights- AmbientLight- DirectionalLight- PointLights- Shadows- Textures- Loading textures with useTextures- Tips and tricks- Misc- Orbit Controls- Loading models with Cientos- Debugging your scene- Performance
Building Vue forms with VeeValidate
Vue.js London Live 2021Vue.js London Live 2021
176 min
Building Vue forms with VeeValidate
Workshop
Abdelrahman Awad
Abdelrahman Awad
In this workshop, you will learn how to use vee-validate to handle form validation, manage form values and handle submissions effectively. We will start from the basics with a simple login form all the way to using the composition API and building repeatable and multistep forms.

Table of contents:
- Introduction to vee-validate
- Building a basic form with vee-validate components
- Handling validation and form submissions
- Building validatable input components with the composition API
- Field Arrays and repeatable inputs
- Building a multistep form
Prerequisites:
VSCode setup and an empty Vite + Vue project.
Building full-stack GraphQL applications with Hasura and Vue 3
Vue.js London Live 2021Vue.js London Live 2021
115 min
Building full-stack GraphQL applications with Hasura and Vue 3
WorkshopFree
Gavin Ray
Gavin Ray
The frontend ecosystem moves at a breakneck pace. This workshop is intended to equip participants with an understanding of the state of the Vue 3 + GraphQL ecosystem, exploring that ecosystem – hands on, and through the lens of full-stack application development.

Table of contents
- Participants will use Hasura to build out a realtime GraphQL API backed Postgres. Together we'll walk through consuming it from a frontend and making the front-end reactive, subscribed to data changes.
- Additionally, we will look at commonly-used tools in the Vue GraphQL stack (such as Apollo Client and Urql), discuss some lesser-known alternatives, and touch on problems frequently encountered when starting out.
- Multiple patterns for managing stateful data and their tradeoffs will be outlined during the workshop, and a basic implementation for each pattern discussed will be shown.
Workshop level

NOTE: No prior experience with GraphQL is necessary, but may be helpful to aid understanding. The fundamentals will be covered.