0 to Auth in an Hour Using NodeJS SDK

Rate this content

Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.

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 for subsequent client requests, validating / refreshing sessions

At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.

Table of contents

- A quick intro to core authentication concepts

- Coding

- Why passwordless matters


- IDE for your choice

- Node 18 or higher

63 min
10 Apr, 2023


Sign in or register to post your comment.

AI Generated Video Summary

This Workshop focuses on adding passwordless authentication to a node application, covering basic authentication concepts and the importance of authentication for application security. It explores session management using server-side sessions and client-side tokens like JWTs. The Workshop demonstrates the implementation of various authentication methods, including one-time password and OAuth. It also discusses the validation and refreshing of session tokens, as well as the customization of authentication methods and the storage of public keys for multiple instances.

1. Introduction to Authentication Workshop

Short description:

In this workshop, we will be adding passwordless authentication to a standard node application. We will cover basic authentication concepts, the importance of authentication for application security, and how to incorporate authentication into a node application. By the end of the workshop, you will have a better understanding of the authentication workflow and be able to add authentication to your own applications.

Let me start with introducing myself. My name is Asaf. I'm a software engineer at Dscope. Dscope is an authentication platform that helps all developers facilitate authentication in a secure manner.

In the next workshop, we are going to add a passwordless authentication to a standard node application. We are going to start by overviewing some basic authentication concepts and basically to go over the flaws that we are going to add. This is like a background and knowledge that needs to that we need to acquire in order to incorporate the authentication properly. And this will probably take about 15 minutes and in the rest of the time, we are going to take an existing application and it's the authentication layer for it.

If you ask what's in it for me in this workshop. So I believe that by the end of the workshop, you will be you have a better understanding of the authentication workflow. This is something that may seem a bit intimidating at start, but I think it's quite simple if you go over it well. And maybe more importantly, I think you will be able to take a standard of application and add authentication on top of it. If you have any node application, you can take it and add authentication in a few steps.

Like I said before, we start with the core concept and afterwards we are going to do the coding and I'll give more information about that later. Hello to the person who wrote the chat. I'm very excited as well. I'm going to assume that you have a basic understanding on Node and the Express framework. The application is written in TypeScript. So, probably if you also know JavaScript, I think it's enough. We don't heavily use TypeScript, but the Node application will be written in TypeScript. Also, just to prepare for the coding session, if you want to do it on your own, you should have a GitHub account, any ID that you choose to code on, and Node version 18 or higher. So, this is up to you, but of course, I'm going to do it here, so this is optional, of course.

Let's start with covering the very basic concept. So, what is authentication? What authentication is? The way I see it, authentication process is basically verifying someone's identity. The internet is a very distributed place, so if someone on another machine says that there are some someone, whether it's a user or a system or a device, they basically have to prove it before they want to access the application, the application, specific resource on the application or the system. This is a very, very essential aspect of the application security. And this is a, we use the authentication layer basically to protect our system for unauthorized access. And this is something that is super important in the digital age. There are so many data breaches, identity thefts in the world. Doing proper authentication is crucial for your application security.

2. Authentication Importance and Factors

Short description:

We will discuss the importance of investing in secure applications and the different authentication factors, such as something you know, something you have, and something you are. Additionally, we will explore new factors like geographic and behavioral factors. After verifying the proof and identity, the application grants the user access through a session or token.

And we hear more and more about incidents of unauthorized access. And if we want to write a secure application, we should invest in it. Just as a side note, we have a really good learning center with a lot of graphical assets there. I sometimes go back there and refresh my memory. And there is a link in the presentation which is also going to be shown.

So what are we going to build? And this is more related to the flows that we want to add. If we break down the parts of the steps of authentication, we can basically break it down into two major steps. The first step is when the user wants to access the resource or the application in the first time, they should authenticate. So usually it starts by a user wants to access the resource. He submits some kind of request to access. The user usually provides its identity. This can be more basically an email, a username. Mobile number, social security ID or what? This is very application specific. And a proof is usually something that basically as you prove who you are.

There are a few authentication proof factors that usually they call factors. An authentication factor is basically based on something you know, for example, a password or maybe a security question. By the way, a quick tip in security question, usually if you care about security, don't answer the real information because usually this is something that is very simple to get this information, like your pet name, etc. Another authentication factor is something you have, a very common example for this is a mobile device. So if I send you an SMS with a code, and then you give back the code to me, I can say, this is basically proof that you have a mobile device. And also something you, basically something you are or something you inherit. This is a relatively new factor of biometric information, either with a fingerprint or face recognition. I also heard about solutions that scan iRetina and stuff like this. Did someone have an idea or heard about more authentication factor other than the three that we mentioned? Something you know, something you have, something you are?

So just like, and just to share from our experience, there are somewhat new factors of a geographic factor. So basically, if you log in from a certain geographic location, this is something that usually makes you either suspicious or not suspicious. If you heard about an impossible traveler scenario when a same user accesses the same application from both locations, that basically a person cannot change the location in that amount of time. And another one is behavioral factor. Basically, if you behave in a way that is not suits you, like you access results that you are not used to access or the rate, this is another factor. So basically, after the application gets the proof and the identity, it's verified, basically check that they match. And then the application grants the user access. This access usually grants in a way of a session or a token.

3. Session Management and Application Description

Short description:

We'll discuss session management and the use of server-side sessions and client-side tokens, such as JSON Web Tokens (JWTs). JWTs are preferred in modern applications for scalability and performance reasons, as they eliminate the need for a single point of access and reduce the computational cost of validating tokens. We'll also describe the application we'll be building, which includes a desktop and web application in React.js, a Node.js server, and an external authentication service. My name is Asaf, and I work with authentication platforms to build secure and frictionless user journeys for various types of applications.

We'll double click it real soon. And usually this token or session is using it in following requests. This is usually done so the user won't have to provide all the proof in every request. So usually you authenticate once, get a token or a session and use it for a certain amount of time. And the verification part after you get a session you usually provide this session or token and the application only needs to validate it.

So if we are talking about session management, we talked about session versus token, there are two technical processes to implement this. One is use server side session and the other user client side token. So a session usually means that the server stores its database, the session information and provides an identifier to the client and in subsequent requests and this session ID is used to retrieve the session information from the database. The server side session is usually very secure, the server which is a secure place has full control over it. For example, if you want to revoke a session, it's something that is a relatively simple to do in server side session, and on the other side there are client-side tokens.

I think someone in the chat mentioned before about JOTS. JOTS are basically the acronym of JSON Web Tokens, and this is a JSON that contains information about who you are, and it signs in asymmetric manners with a private key in the backend, in the server, and the token itself, all the token is sent to the client and in subsequent requests the JOT is basically validated and its information is used to determine, basically the server or the application can use to determine information about the user. Can someone maybe share what do you think are the advantages of client-side tokens, tokens, of JWTs? Okay, so I'll share that basically all all modern applications prefer to use a JWT for scalability manners. And so, basically, if you're talking about microservices architecture, you don't need to have a single point of access to access, for example, a database, and the performance of basically validating JWT is something that is relatively cheap to compute in comparing to accessing a database entity. And this is basically, I think that Kevin also wrote that you don't have to store the server session, and this is absolutely right.

One last thing before we jump into the coding session, let's describe the application that we are going to build. The application purpose, I'll demo it really quick in a minute, is basically to show the user some kind of financial revenue about the customer user organization. It doesn't really matter, but the important thing is that it shows it contains a resource and we want to protect this resource with an authentication layer. The application is composed with a desktop application, a web application, in React.js. We are not going to touch to spend time on the code, but if you want, you can go to the open source repo and take a look. The Node.js application server, this is what serves the information to the client. We are going to use a very simple express server. And another component is the authentication service. This is usually an external service that manages the user identity and authentication. Usually the application is communicating with the authentication service with an SDK library. In this workshop, we are going to use this code as the authentication service. OK. Right before we are starting, a few words about myself. My name is Asaf, as I said before. From this code, this code is authentication platforms that helps all developers to build security, security and frictionless authentication and to build user journeys for B2B apps, B2C apps and basically any app that you have.

4. Introduction to Passwordless Authentication

Short description:

We are focusing on passwordless authentication, offering various authentication methods such as MagicLync, Social Login, SAML, and biometrics. We provide multiple authentication approaches, including no code or some code, and an API. Feel free to ask questions or follow along as we go through the steps. You can clone the repository and use the main branch. We'll start with workshop 01 and progress from there, demonstrating each step of adding authentication. The application uses React for the frontend and Node for the backend.

We are focusing on passwordless authentication, we are offering MagicLync, Social Login by the OAuth protocol, SAML for businesses, one-time password biometrics and more. And we have multiple authentication approach, either no code or some code, and you can also use the API. And if you want to read more about it, just write this scope at Google or go to the scope.com. And that's it.

Beside that, I play Frisbee a lot at my free time, and I love to learn everything I can about astronomy and astrophysics, and I'm a big Almagrid fan.

Okay, so without further ado, let's start. We are going to use the following repository. This is a repository in the Scope SampleApp organization. I'm going to, if there are any questions, feel free to stop me now or write in the chat. I'm going to share the link in the, oh, thank you, Chris, for sharing the link. And so, I'm going to go over the steps that we described before. Basically, I think I have the application running. Okay. So, I already cloned a repository to my computer. Feel free to copy, to clone this repository to your machine. You can use the main branch. Okay? But I already built up front your branches. Let's see all the branches. Like, we are going to start the workshop 01. And then, from there, we are going to progress. I'm going to show each step of adding another part of the authentication in the following steps. You can decide if you want to code it, or just listen to me and go over the steps later. I'm going to use the branches to show the progress. So, let's start. I'm going I already cloned. You can do NPM install. This will install all dependencies, and if you want to see the application running, just run npm run dev. This will open a basic application. The frontend is in React. The backend is in Node.

5. Application Structure and User Authentication

Short description:

In this part, we will describe the repository structure of the application and the unprotected routes. We will then focus on implementing user authentication by building a minimal form in the React application and handling the authentication request on the server side. To interact with the authentication service, we will use a scope and log in to create an account and obtain a project identifier. We will also install the necessary SDK package and create a .n file with the project ID in the server directory.

And basically what this application has, it has a few widgets of basically revenue information. And I'm going to walk with the Chrome DevTool open so we can see the networks and other important information like cookies and the request details.

Let's start with describing how the repository looks like. So we basically have a client folder and a server folder, and I'm not going to cover the client at all. The server has one entry point, indexts, and if you can see what the application does here, basically start by spinning up an express service, and it serves four different routes, and that's it, basically. So right now, those routes are not protected at all, and our goal in this workshop is to add authentication to those routes.

Okay, so the first step that I want to add is basically to have the user a place that they can authenticate. The way we are going to implement this is to build a very minimal form in the application and implement the request to the authentication in the server side. So again, I'm returning to the diagram here. The request to initiate the authentication will go from the React application to the Node backend and to the authentication service. And so the first thing we are going to do is we want to have a way to interact with the authentication service. We can go to our authentication provided. In this case, we are going to use a scope. We can log in. I already have an account, but you can go to this application and create an account. It's free and you can create it. It will automatically create a project for you. You don't need to do anything here in this place, except copy the project identifier. This will be used to identify the project when you're accessing the authentication service.

Okay, so the first thing we are going to do, okay, I'm going to basically check out the first workshop, the branch workshop 01. This is the same as the main branch. And I created the first step already in workshop number two. What I need to do, the first thing I need to do is to run is to go to the server directory. And I want to install this dependency. So I'm going to run npm i minus minus save exact and the name of the package, this is the package, the SDK that will help us to communicate with the scope. And let's see what we've done here. We import it and we just created and we created basically an object, a client auth, that we'll be later going to use to interact with with the scope. Another thing that you can do with your project ID is to create a .n file in the server directory and let's open it. It was already exist. And to create a one entry with your project ID from before.

6. Adding One-Time Password Authentication

Short description:

We will now add the first authentication method, one-time password (OTP), which is typically sent to the user's mobile or email. In this case, we will send it to the email. We will add the code that sends the email and create a POST route named OTP login. The route will use client authentication to handle sign in or sign up with an email. We will ensure the request succeeds and display the response, which includes the code, data, and error information. We will also add a form in the UI to demonstrate the login process.

I'm going to copy the format in the chat if you if you find it useful. Okay. This is basically a way to copy your project ID. You can also put it in the code and whatever you feel more comfortable. Okay. And of course, if I run the sample, after every step, I'm going to run the sample to make sure that it behaves the same. Right now, we didn't do anything important. And in the backend, we just created an instance of the SDK and nothing has changed.

The next step that we are going to do, and the first authentication method that we are going to add is called one-time password. One-time password is usually in code that the authentication service sends to your mobile or email. In this case, I'm going to send it to the email so I can show you in my mailbox here, and we are going to send the code and then we are going to submit it. So the first step that we're going to do is to add the part that sends the email. Okay, so let me check out the branch of Workshop 3. This is the branch that in this branch what we have done, we have basically added a POST route named OTP login. And this route used the client authentication, the client auth to perform basically sign in or sign up or in with an email. Okay, if you want, you can do a phone instead, sorry, SMS instead. We also provided a WhatsApp. But this is basically up to you. I'm going to add an email form. And what we've done is basically we make sure that the request succeeded. And if you use TypeScript, this is very helpful for you to see the response. So, you can see what the response contains. Basically, an object with an SDK response, which basically is containing the code, if the request succeeded or not. And the generic data and error information if there is an error. And so, I also added a form in the UI. Let's see it. Okay? Just going to navigate to and this is the form that I've added. And we can see that if I logged in, I got 200 requests. And this is basically send me this code. And the next step that we are going to do is to take this code and to verify the user using this code.

7. Adding One-Time Passcode Verification

Short description:

In the next branch, we added another route for one-time passcode verification. This route validates the email and code from the UI, and shares the authentication information with the browser. The function takes the express response, SDK response, and SDK output, sets the cookies and session JWT, and returns them. The SDK returns the session JWT and additional cookies, such as a refresh token. Let's see it in action.

Okay? So, let's go to the next branch. Okay? In the next branch, we added another route of one-time passcode verify. This route gets the email and the code from the UI. And it uses another method of, to verify the email. And again, check for error. And the important information after this is we want to share the authentication information from the response to the browser. The way that it's done, this is a short function that we wrote. It takes the express response and the SDK response and the SDK output. And what it does, it basically set, take the cookies and the session JWT, and return and set the cookies for from this information. The SDK returns the session JWT on the response and extra cookies for other use for example, a refresh token, maybe here. And what we want to do is to add the cookie to the response. Let's see it in life.

8. User Authentication and Cookies

Short description:

When logging in, the response returns a session cookie and a refresh cookie. The session cookie is set automatically, while the refresh cookie is returned in the cookie object. The refresh cookie is the session token that identifies the user and may contain additional information about the user, such as roles or tenants. It is an object with a signature that contains user information.

Okay. So, let me delete the previous mail. If I'm log in right now, I've also added in the UI a code form. And once I get the email, the code from the email, and enter it, right now, I can see that in the response, the response returns two cookies. It returns a session cookie and another refresh cookie. The session cookie is the one that we set here automatically. And the refresh cookie is the one that this call returns in the cookie object. And I'm going to talk about refresh in a bit. The refresh is usually the session token, is the one that chooses to identify the user. It contains, it may contain more information about the user, like its roles, or if it's a B2B app, it may contain its tenants and other custom claims. I'm not going to cover too much about JWT, but in like a few sentences, this is an object with a signature, and the object contains information about the user, who the user says that they are. And let me know if you have any questions and I can elaborate on that.

9. Protecting User Data with Middleware

Short description:

We saw that the cookie returned to the application and is automatically set in every request back to the server. Now, we need to add a middleware to protect the authenticated user's data. The middleware parses the cookies, extracts the refresh and session tokens, and uses the client auth SDK to validate the session. If the signature matches the JWT information, the request context is created.

Okay, so we saw that the cookie returned to the application. We can also see in the Chrome DevTool that we have the cookies here, the session cookie and the refresh cookie, and we can see that in every request that we send back to the server, those cookies are automatically set. So the server set the cookies on the response. And from that on, all the requests back to the server are containing those cookies.

So, I think now it's a good time for the major part, and the important part about authentication is basically to protect those results. Right now, we've done the first part of authenticating the user. The user is authenticated, but we still didn't check that the user is verified. So, what we want to do now is we want to add a middleware in front of all those routes that will make sure that the user is authenticated. Let's see how it looks like.

So, we added the following code. We have here a function. This is an express middleware, and we're going to cover it in a bit, and we've created the DedicateRouter. The router, we will run the middleware before each request, and we change all the APIs that we want to protect that we want to protect to run on this specific router. Let's see what this middleware does. This middleware basically takes the request and the response and what should run afterwards. The middleware can decide whether to run the next function, which in this case is the function that returns the data, or not. So let's see what the middleware does. The first thing is it parses the cookies. The cookies are on the request. We set it in previous steps, so we can see basically a very simple code that takes the request, takes the cookie and breaks it down. I wrote it here in plain code so we can see what happens under the hood, but there are many dedicated packages for these purposes, for example, CookieJS and other Javascript libraries that can do it for you. Afterwards we are extracting the refresh and the session token and we use the client auth, the SDK to validate the session. What this action will do, it will take the session and will make sure that the signature matches the information of the JWT. If you haven't seen JWT before, it contains three parts that are encoded in Base64. The first part contains a metadata about which algorithm to use and other information about the token. The middle part contains the information about the user, the user's ID, and maybe stuff like roles and other custom information. And the last part is the signature. So what this part will do, it will validate the signature matches what the user says they are. And if this part basically succeeded, we created the request context. By the way, up here we declared how the context should look like if you are interested.

10. Session Token and Refresh Token

Short description:

A refresh token is used to communicate with the authentication service and generate a new session token. It doesn't contain user information and should be treated as a secret. The session token is also sensitive and should be securely stored. If session validation fails, the SDK throws an exception and attempts to refresh the session. If the refresh fails, an unauthorized response is returned. The refresh token middleware runs before every request, ensuring the user is communicated with the new session token. In incognito mode, requests fail due to the lack of cookies. The SDK validates that the session and access tokens are not expired.

And this is a way to express, to articulate basically in TypeScript to articulate how we want the request context to look like. And we added this information here. The question is basically, usually a refresh session token is valid for a certain amount of time. It's valid for five minutes or 10 minutes. But usually this is done for security reasons because we don't want session to be, once a session is signed and generated, it is valid until it expires.

So the session validation time is usually about five to 10 minutes but we don't want the user to authenticate every 5 to 10 minutes. For that purpose, there is the refresh token. The refresh token is used to communicate with the authentication service and generate a new session token. This is its purpose. Usually, it doesn't contain information about the user and should be treated as a secret. Also, the session token should be used as a secret but this is very sensitive information so it should be kept in a very secure manner. For example, all the cookies are set as an HTTP-only cookie and as secure cookies. This is also something worth mentioning. If the session validation failed, the SDK will throw an exception. The middleware will fall back to try to refresh the session.

We tried to refresh the session. If the refresh failed, we return an authorized response. And if the refresh manages to succeed, we want to set authentication cookies like we've done in the authentication because we wanted to communicate the user with the new session token. And that's it. Again, this refresh token is this authentication middleware runs before every request. Let's see it in live. Okay, I'm going to refresh the page. And we can see that we are still getting the information. I want to also go to incognito, and to see what happens when we submitted request here. We can see that we are getting 401. The reason is because the cookies are not maintained between incognito or window, we can see that we don't have any cookie here. And because we haven't sent the authentication, we haven't sent the notification information, all requests failed.

I see that there is a question in the chat. And doesn't the validation of Jot also check that the Jot access token is expired? This is a very good question. Yes, the SDK function that we saw here also validates that the session is valid and didn't expire.

11. Session Details and Expiration

Short description:

We can examine the session details on the Jot.io website. The session consists of metadata, payload, and a signature. The payload contains information such as the issuer, project ID, and user ID. It also includes an expiration time. We can see the expiration time of a token by looking at the payload.

Every session, we can take a look here. Let's take a look here on the session. I'm going to copy it. There is a nice website called Jot.io. And you can see that those are the three parts that we've discussed before. Metadata, the headers of the JOT. This is the payload, it contains, this is basically the issuer, this is the project ID, in the scope. This is the user ID and there can be more other metadata in this, and the third part that we see in blue is the signature. You can also see that a part of the payload is when it expires. So for example, this token expired in basically two minutes ago, if I'm not mistaken.


Session Validation and Refresh

Short description:

The session validation generates a new access token if it's expired. A refresh request is submitted if the validation fails. JWT tokens are validated by downloading a public key. The Validate and Refresh functionality returns cookies and handles the necessary work for you.

Okay. Here is another question. So the session validation is about to generate a new access token once it's expired. So for the second question, the session validation doesn't do it alone. For this purpose, we have created a refresh. If the session validation fails, we create, we submitted a refresh request to get a new session. By the way, the SDK also supports, I'm sorry, validate and refresh session in the same part. It's basically encapsulate the parts that we've seen here for you.

Omkar, go ahead. Unmute yourself. In the validate session function, does it simply validate the JWT token or does it make a call to authentication server to validate the token? So, for JWT tokens usually validated, they are not validated in the backend, but the way that it's done, the validation is done by downloading a public key. The way JWT is built is built with a private key and generated with a private key and validated with a public key. What the API does under the hood is download once publicly and it uses it to verify the signature of the token. I hope that answers the question. This basically done the download of the public key is basically done once. There is a protocol about how to verify JWT, a very interesting topic. There are other aspects of, maybe we can see it here. Usually there are other information about the JWT, like what is the key ID, because usually the service provider, the scope also does it. It rotates the public keys for security reasons. So every public key is downloaded once. Okay, got it. Thanks.

Yeah. And another question is whether Validate and Refresh also rewrites the cookies that go into the client. So the Validate and Refresh also returns cookies. And when we made this session, like full disclosure, when we made this session, we find out that there are a few gaps in the Validate and Refresh functionality. This is one of the reasons that I'm demonstrating this in this manner. But yes, ideally, the Validate and Refresh will do all this work for you, and it will return the cookies, and then you will be able to take the cookies and put them on the user request. Let me continue. We have just saw how we protect the route.

Authentication Flows and OAuth Protocol

Short description:

In this section, we covered more use cases of authentication flows, including the implementation of a logout route. The logout route clears the cookies and signals the browser to clear them as well. We then discussed the OAuth protocol, which delegates authentication to another identity service. We explained how OAuth works and added routes for starting authentication with Google and redirecting back to our finish route.

This is basically what we've covered in the flows that we've discussed. Usually, to expose, because we have a bit more time, let's show more use cases of the authentication flows.

Another thing that we want to do when all users is usually we want to enable them a way to logout. So I've also implemented a logout route. Note that the logout route is also an authenticated route.

Let's see what it does. It takes the refresh token from the context and it calls the logout. This process will basically indicate to the authentication service that you cannot use this token to refresh any sessions. And afterwards, it clears the cookies from the request. So the browser will also clear them.

We can see it here in live. I've also added another button here that triggers the log out. You can see that once I log out, once I press log out, I activate the log out functionalities. And you can see that I've got an empty cookies, which basically signals the browser to clear them. And if I'm going to the main page, I won't get any answers.

Okay. And let me continue by covering another authentication method that I want to talk about, which is OAuth. OAuth is a protocol that delegates authentication to another identity service. Usually, we use social accounts for this, for example, when you log in with Google or log in with Twitter or log in with Facebook, this uses the OAuth protocol.

In a few words about the OAuth protocol, how it works, the application delegates the authentication to another service. It redirects the user to another service and it gets back a code or maybe a token. And it takes this token and generates, after it gets the token, it verifies this token and creates a JWT session token and JWT refresh token.

The terms here are a bit confusing because there is the OAuth token and there is the session token. So this may be a bit confusing. Let's see it in practice and I think it will be a bit more clear. We added here two more routes. One is when the user pressed, for example, signing with Google button. We trigger an API call to the authentication service to start authentication with Google. And we tell the service that after the authentication is done, we want to redirect it back to our finish route. And after a successful start Google, we redirect, we get back the URL.

OAuth Authentication with Google

Short description:

We redirect the user to the OAuth start route, where they are taken to the Google authentication page. After authentication, the user is redirected back to the application with a code. This code is exchanged with the session, and cookies are set in the same manner as before. Authentication works as expected, and no changes were required in the authentication middleware.

And we redirect the user to this URL. And let's see it in life. Okay. Sorry. Okay. So I've added another button here in the UI. This will trigger the OAuth start route. And you can see that basically what it does, it takes the user to account google.com. OAuth 2, this is the protocol. And now the authentication is done with Google. Okay. And once I authenticate it, I've redirected back to this code. And this part redirected me back. It took the code from the query. This is the code that we transferred with the session. And then we exchange this code that we got from Google in this case with the session. And afterwards, we set cookies in the same manner and we redirect the user back to the application. Okay, so and you can see that authentication works as before and nothing is changed in that manner. And we didn't have to change anything in the authentication, in the authentication middleware.

JWT Token Validation and Performance

Short description:

The server stores the public key in memory using the SDK. The public key is not secret and is used to validate the JWT signature. It is lightweight and has minimal impact on application performance.

Okay, any question about what we've done so far? In the JWT token, you mentioned that the JWT token is created using the private key and then it is validated using the public key. So does the server store the public key in memory or with it? Yeah, the SDK basically, this object client auth, this is the SDK. It stores it internally in the memory. Just to iterate the first two things, this public key is not secret, anyone can access it. And its only purpose is to validate that the signature of the JWT matches the information that the user, that is in the payload. This basically proves that the JWT was generated with the matching private key. Wow. And the other thing that I want to mention is that this public key is very lightweight and it doesn't affect on the application performance. It's very low.

OAuth and Frontend Authentication

Short description:

OAuth is a protocol that involves an external identity service and the generation of tokens. The application takes the user to the identity provider, retrieves a code, and generates a JOT. We have a different approach where authentication is done from the front end to the authentication service. This involves removing authentication methods and using a minimal middleware for validation. The React SDK is added to the front end, and a scope component controls the authentication process.

Okay, another question. What is different? Here, the OAuth, we have an external identity service, the generation of the token. So this is a very good question. Basically, it's related to the purpose of OAuth. And the OAuth doesn't... The output of the social login is only to generate the code. The code, this is basically something that moves to the identities. In OAuth, OAuth is a vast protocol, but basically, beside the user, there is the service provider, which is the application that we have here. Sorry, this is the application that we have here, and the identity provider. Identity provider, in this case, is Google. So, the application takes the user to the identity provider, it gets back the code, and the responsibility to generate the JOT is still on the service provider, which in this case is the Node application that we have. I think if you want to read a bit more about OAuth, we have really good articles in the Dscope blog. So, I would recommend to read more about it there.

In the minute that I have before I'm answering more questions, I want to present a different approach to what we've done here. So far, we saw an approach that the authentication is done directly from the application server to the authentication service. There is another approach that we believe is a bit more flexible and simple to incorporate, which is done from the front end directly to the authentication service. So you can see that I removed all the authentication methods, the OTP and the OAuth. I left with a very, very minimal middleware that does only the validation and all the work of showing the forms and managing the tokens is done with the front end. I'm not going to cover it too much because this is basically done in React. This is not the scope of this workshop. But the TLDR of it is that we basically add the React SDK in the front-end side. We wrap the application in authentication provider. And then instead of the flows, sorry, instead of the forms that we saw before, we just add minimal scope component. And this component basically controls everything. I think I forgot so I think I forgot to install the React app. Okay. So this form is completely no code. You can go to basically, to the scope application and go to the flows page and control the screens and the authentications flows directly from here. So this is the screen that we see here in the application. It's very simple to embed it.

Customizing Authentication Methods and OAuth Flow

Short description:

You can customize the authentication methods in the scope UI, including adding biometrics. The UI allows for complete control over the application layout and the addition of steps, such as signing up or logging in with biometrics. No changes are required in the front end or back end for authentication to work. The OAuth protocol redirects users to the chosen identity provider, such as Google. The provider validates the code, and if successful, generates a session job.

And you can control the authentication methods that you want to add in the scope UI. We believe this way is much more flexible and simple to do. For example, if you want to add another authentication method, such as biometrics, all I need to do is to add here, for example, a biometrics button. This UI is highly customizable. For example, I can completely control over the layout of the application and I can add another step here of biometrics, okay? For example, sign up or in using biometrics, connected with a very simple drag and drop experience. And once I press save, I can see the changes over here. This is something that is now, for example, I can use this to authenticate and this is, I didn't have to change anything in the front end or in the back end. Authentication will work in the same manner.

I think that this is what I have to show in the workshop. I'm available for question here. And before that, I want to say thank you. Thanks a lot for everyone, for your participants. It was a pleasure to meet you.

Hi, what you were describing last time was there is a way to that the front end application takes the token directly from the identity server or the code, and that code will be the security code that will use as a code to communicate secure with the backend. That code will be validated from the backend to the identity server. When I'm speaking here identity server, I'm speaking as an entity that's not part of the server that we are using. It can be Google, it can be Amazon, it can be other entity, right?

Right. You mean to the OAuth flow, right?

Yes, exactly. Right, so yeah, you are correct. The OAuth protocol redirects the user to the identity provider in this case was Google. Identity provider in this case was Google. You make the authentication with Google. Google, in its turns, takes the user, let me show it in the code, takes the user back to the read identity provider, direct URL with the code as a query parameter. And the application takes this code, validate it against Google. And if the validation against Google succeed, it will generate a session job. I hope this answers the question.

Yeah. Thank you very much for clarifying all my questions.

Not a problem, it was a pleasure. Another question in Jot Auth.

Storing Public Key for Multiple Instances

Short description:

When using multiple instances of a server or a stateless server, you don't need to worry about storing or managing the public key. The SDK automatically handles the process of downloading the matching public key from the authentication service. This functionality is not bound to any specific instance and can be performed from a serverless function.

How to store a public key if you are using multiple instances of the server or a stateless server? So this is something that you don't have to worry about. It's completely transparent to you. You only need to call the validate session and the validate session will automatically... Basically what it will be. Let's maybe take an example for a session here and go to JotIO, okay? So it will take the key ID from the header and it will download the key ID and the issuer and the key ID and it will download from the identity service. It will download... Sorry, from the authentication service, it will download the matching public key. This is how it is done. You don't need to worry about storing it or managing it. The SDK does it automatically. And this is not bound to any specific instance. It can be done from a serverless function without any problem. Great, so one last time, I want to say thank you all.

Watch more workshops on topic

React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?
In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.
Node Congress 2023Node Congress 2023
109 min
Node.js Masterclass
Have you ever struggled with designing and structuring your Node.js applications? Building applications that are well organised, testable and extendable is not always easy. It can often turn out to be a lot more complicated than you expect it to be. In this live event Matteo will show you how he builds Node.js applications from scratch. You’ll learn how he approaches application design, and the philosophies that he applies to create modular, maintainable and effective applications.
: intermediate
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.

React Summit 2023React Summit 2023
56 min
0 to Auth in an hour with ReactJS
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.
JSNation Live 2021JSNation Live 2021
156 min
Building a Hyper Fast Web Server with Deno
Deno 1.9 introduced a new web server API that takes advantage of Hyper, a fast and correct HTTP implementation for Rust. Using this API instead of the std/http implementation increases performance and provides support for HTTP2. In this workshop, learn how to create a web server utilizing Hyper under the hood and boost the performance for your web apps.

JSNation 2023JSNation 2023
104 min
Build and Deploy a Backend With Fastify & Platformatic
Platformatic allows you to rapidly develop GraphQL and REST APIs with minimal effort. The best part is that it also allows you to unleash the full potential of Node.js and Fastify whenever you need to. You can fully customise a Platformatic application by writing your own additional features and plugins. In the workshop, we’ll cover both our Open Source modules and our Cloud offering:
- Platformatic OSS (open-source software) — Tools and libraries for rapidly building robust applications with Node.js (https://oss.platformatic.dev/).
- Platformatic Cloud (currently in beta) — Our hosting platform that includes features such as preview apps, built-in metrics and integration with your Git flow (https://platformatic.dev/). 
In this workshop you'll learn how to develop APIs with Fastify and deploy them to the Platformatic Cloud.

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

Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Do you have a large product built by many teams? Are you struggling to release often? Did your frontend turn into a massive unmaintainable monolith? If, like me, you’ve answered yes to any of those questions, this talk is for you! I’ll show you exactly how you can build a micro frontend architecture with Remix to solve those challenges.
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Remix is a web framework that gives you the simple mental model of a Multi-Page App (MPA) but the power and capabilities of a Single-Page App (SPA). One of the big challenges of SPAs is network management resulting in a great deal of indirection and buggy code. This is especially noticeable in application state which Remix completely eliminates, but it's also an issue in individual components that communicate with a single-purpose backend endpoint (like a combobox search for example).
In this talk, Kent will demonstrate how Remix enables you to build complex UI components that are connected to a backend in the simplest and most powerful way you've ever seen. Leaving you time to chill with your family or whatever else you do for fun.
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
JavaScript in the browser runs many times faster than it did two decades ago. And that happened because the browser vendors spent that time working on intensive performance optimizations in their JavaScript engines.
Because of this optimization work, JavaScript is now running in many places besides the browser. But there are still some environments where the JS engines can’t apply those optimizations in the right way to make things fast.
We’re working to solve this, beginning a whole new wave of JavaScript optimization work. We’re improving JavaScript performance for entirely different environments, where different rules apply. And this is possible because of WebAssembly. In this talk, I'll explain how this all works and what's coming next.
React Summit 2023React Summit 2023
24 min
Debugging JS
As developers, we spend much of our time debugging apps - often code we didn't even write. Sadly, few developers have ever been taught how to approach debugging - it's something most of us learn through painful experience.  The good news is you _can_ learn how to debug effectively, and there's several key techniques and tools you can use for debugging JS and React apps.
Node Congress 2022Node Congress 2022
26 min
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Do you know what’s really going on in your node_modules folder? Software supply chain attacks have exploded over the past 12 months and they’re only accelerating in 2022 and beyond. We’ll dive into examples of recent supply chain attacks and what concrete steps you can take to protect your team from this emerging threat.
You can check the slides for Feross' talk