0 to Auth in an hour with ReactJS

Rate this content

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.

56 min
15 May, 2023


Sign in or register to post your comment.

AI Generated Video Summary

This is a React Node.js workshop that covers implementing Dscope authentication in a React project. It explains how to set up a Dscope account and customize authentication flows using the Dscope console. The workshop also covers using React Hooks and the Dscope provider, adding dynamic login and logout functionality, protecting data with session tokens, and validating sessions with Node.js middleware. Additionally, it demonstrates how to customize authentication flows in the Dscope console.

1. Introduction to Dscope Authentication Workshop

Short description:

This is a React Node.js workshop that we do bimonthly or once a month. Today, we're going to show you how easy it is to implement Dscope authentication in your React project. We'll cover core authentication concepts and then get into coding our sample application. Prerequisites include a basic understanding of React, Node.js, Express, and having a GitHub account. Authentication is verifying the identity of a user device attempting to access an application or system, while authorization is verifying a person's access rights. We'll provide a high-level overview of how authentication works, including the use of access tokens. Dscope operates as an authentication service, handling the authentication process for your projects. We'll show you how to use Dscope, set up your account, and create your first flow.

But my name is Kevin. I work at Disco and I'm here today to present our zero-to-often-an-hour workshop. This is a React Node.js workshop that we do bimonthly or once a month. And this is the third rendition of this. It's we're going to show you how easy it is to kind of implement Dscope authentication in your React project.

So we have an agenda today. I'll get to that in a second. First just a little bit about me to introduce myself. So my name is Kevin. I work at Dscope. I live in San Francisco. Things I like to do outside of work. I love driving, working on cars, love traveling to many different countries. I'm very passionate about tutoring and helping kids with math. But yeah, so for our agenda today, we're going to go over two things. First we're going to kind of gloss over a few core authentication concepts. Just to kind of clear the air and make sure that everyone's on the same page about what authentication is and thus forth. And then we're actually going to get into to the coding of our sample application that we've prepared for today's workshop. So we have a React frontend and a Node.js back end sample application that I'm going to show you guys. In order to kind of follow along with this, there's a few prerequisites that I should mention. So one, I think a basic understanding of React, Node.js and Express I think will be helpful, as well as having a GitHub account. So we're actually going to provide a link where you can clone the repository that we have if you haven't already done so. So that will be helpful. And then an ID of your choice, I'm going to be using VS Code for the coding section, and Node 18 or higher to actually run the sample app is So getting into it though, I want to make sure that everybody's on the same page with what authentication really is. So I'm sure a lot of you guys, especially those who are engineers, you know, are already familiar with it. But authentication is a word that's kind of freely thrown around by a lot of people and sometimes used interchangeably with authorization. So authentication, put it simply, is basically just verifying you are who you say you are. The definition I have here is verifying the identity of a user device attempting to access a particular application or system. And so if you imagine you're at an airport and you are kind of going through security at the beginning and you show your passport or driver's license or something like that, that is kind of the first step towards getting on the plane. And then authorization, which is usually used in tandem with authentication afterwards, is verifying a person's access rights. So after the user has been verified, they say they are, then you need to check if they have the rights to do or see a particular application So going back to the airport analogy, that would be like being at the gate and providing your boarding pass to get on the plane because maybe you are who you say you are, but maybe you're not allowed to be on that specific plane. I just want to make sure that we understand the difference between authentication and authorization. You'll actually see both of those. You'll see a mix of both of those in this workshop. But if you want to learn more about specific authentication concepts, you can visit our learning center at cscope.com slash learn. We have a lot of great articles there about more like the specifics about how it works, like how JSON Web Tokens are structured, how authentication authorization servers actually work in the backend and things like that. So I'd highly recommend if you're interested in learning more about authentication outside of the scope of this, this workshop, definitely check that out.

So getting into it now that we kind of understand, you know, what authentication is, this is a high-level overview of how it can work in a very basic sense. So if you're, you know, like let's say trying to, you know, log in to your Gmail account or something like that, the browser will, usually the user will provide credentials and that will be passed from the browser to the server. The server will validate those credentials. It can be a password. It can be OAuth log-in, something like that. And then, you know, once the user is successfully verified, that will return some form of access token, usually as a cookie, but it can also be stored in the browser's local storage. And then on the browser side, all of that will, all of that would be handled so that for every subsequent request, if you're logging into Gmail and then you want to look at specific emails, or you want to change something, some configuration your inbox or something like that, all of those requests are, you know, authenticated requests, or that are requests that need to be authenticated, and that access token is used to validate you are who you say you are and be able to do that. So kind of going off that, just the kind of key components of authentication are, you know, the user, me, who's logging into Gmail, the desktop or mobile device I'm using, my requests usually will get sent to some kind of app server, which will then pass on my credentials, my username and password or something to an authentication service. So that's what Dscope operates as. We operate as an authentication service, we handle everything so that, and then that gets passed down back to the desktop or mobile device that the user is using, so that you don't have to worry about that. I'm going to actually show you guys how to use Dscope, how to set up your account, how to create your first flow and show you how easy it is to customize it eventually. So let's Dscope our project. Dscope being, our idea is we want to take away the responsibility having to worry about that, about the authentication aspect of your projects and we can handle it for you and you can worry about the rest.

2. Setting up Dscope Account and Authentication Flow

Short description:

This section explains how to set up your Dscope account and use the Dscope console to build a flow for your authentication. It covers signing up with DCO, accessing the console, and using the getting started wizard to customize your authentication methods. The wizard allows you to choose between business and consumer applications, select authentication methods, and optionally enable multi-factor authentication. The shortened version includes the key steps and concepts without going into excessive detail.

So this link right here at the bottom which hopefully Chris or Asaf can put in the chat, this will take you to our repository that you can clone and that we're going to be working for the remainder of this workshop.

Before we actually get to the coding, the reason why it says What's Dscope is we actually want to show you guys how to set up your Dscope account because we're going to need to do that. So let's get into it.

So if you guys can open up a web browser and go to www.dscope.com sign up. Someone can paste that in the chat as well. This will take you to our main website, which you can see will look actually for you something like this. I have an incognito window up. So I'm not logged in. And then you'll be able to sign up with your email or with Google or Microsoft, whichever you prefer. And so we're just going to sign up for DCO. This is going to bring us to our console where we can build our flow. So I'm going to sign up with email just like you guys. Sign up for a new account there.

Okay. And then take this. And then put in my name. Now create my account. So here it just sends a magic link to your email and then you should be able to see you to be able to see. Thanks for signing up. A Disco console is a quick way. Let us, a staffer, Chris, know if you have any issues with that. But but yes, the ones, once that once you signed up, very simple process, you click let's go. It's going to open up the disco console. And since we have a completely new project, it's going to take you straight to hi there. In just a few easy steps, you can build passwordless user journeys in less than 10 minutes.

So this is our getting started wizard. This is what's going to we're going to ask you two simple questions. It's going to actually build out a login page that you can put in your react or WebJS applications. And it's going to give you the code snippet for that. And it's also going to create a flow that you can then edit and change to customize your authentication. So just press getting started. And I'll actually expand this out. So it's going to say who uses your application. Businesses or consumers. So this is this is a simple question, depending on if you want to use tenants or not, for the scope of our particular sample app, I think consumers is fine, we don't need to worry too much about business B2B authentication. And then it's going to ask you which authentication methods you do want to use. You see here, it says B2C because we selected consumers, and we can choose up to two methods that will appear in the login screen. So I'm going to select social login and one time password. I think social login, like signing with Google, a lot of websites use this. It's really easy to use, really simple. And especially if you're using Chrome or a browser where you have Microsoft or Google sign in, this would be really easy to use. And then one time password, because it's also very, relatively straightforward and straightforward to send you a password for your email or your phone number, and then it allows you to log in. Then it's going to ask if you want to use MFA. So MFA is multi-factor authentication. It's a second layer of security. If you want to add that, you could add something like biometrics. You could add magic link, something like that. For now, again, for the scope of our particular application, we're not really going to use this. I should also mention that in our actual application, I've prepared a different flow. So I'm going to walk through this and show you guys how to create this.

3. Dscope Account Setup and Authentication Flow

Short description:

In this section, we will explore different options for the login screen and the end-to-end structure of authentication flows. We will focus on the sign up or sign in flow, which combines both functionalities. Additionally, we will discuss the required React components and the server-side code for validating sessions and building authentication middleware. We will also examine a customized flow in the Dscope console and the associated unique project identifier. Finally, we will review the flow of authentication, including the welcome screen, authentication with Google or Microsoft, and signing up or signing in with email. The flow concludes with the generation of session JWT and refresh JWT tokens.

You can use this for your own projects, but for our projects, I'll show you we're just going to use another flow that I've already created, and I'm going to show you how to do that. It's very simple. But let's just go ahead with that MFA for now because it's a pretty straightforward flow we're building here.

And then it's going to give us a few different options for a login screen, and this is based on the stuff that we, the selections we made previously. We can just select this one. It just says welcome with the continued Google Microsoft button. This is all totally customizable. I'll show you guys towards the end how you customize everything. But you know, we can just select this one, looks good, click next.

And then this is where we're getting into the meat of the wizard. So after all those questions that it asks you about how you want it to configure it, this is our end result packet. This is our login page, which has a full-fledged authentication behind it. And it's going to create these four flows based on the information that you gave previously. So these flows, you can think of a flow as just the end-to-end structure of how your authentication works. So you want the very first thing to be a welcome screen like this, and then when you click on Google, do you want it to use OAuth to sign in? And then from there, do you want to do something if it's a new user, do something if it's an existing user? So that's the idea of a flow. And I'll show you guys what that looks like in a second.

But sign up or in is what we are going to focus on now because that's a single flow that combines the sign in and sign up functionality. So these other ones are obviously good for specific use cases, but I think for a server sample app, we just want to have everything in one flow. And then when I click next, it's actually going to build all of those flows and I can show you in the flows screen here what that looks like. So this, at the end of the Getting Started wizard, will give you run the actual login page. This is the actual React component that you're going to be using that's associated with this project. This is the one we saw earlier. And this is actually a full fledged React component right here that you can actually log in with and you can see the response. I'll show you that in the flow that we're going to use.

But, as you can see here, these are the React components you're going to need. This is the author provider wrapper that we're going to actually be putting in our project. And then for our backend, for our server, this is, since we're doing a Node.js server, this is basically the code that we're going to use to validate the session and build out the authentication middleware. So let me just quickly show you guys. So this is, okay, yeah, so what we want to do is you won't be able to see this, because I've already prepared a flow, but I'm going to actually click out of this and go back to my account to show you guys what we're going to be working with and what that looks like. You can follow along on your own screen, but basically, this is where we kind of left off in the wizard, and you can see it looks a little bit different because I have customized it myself. I have email login and I have Google and Microsoft, and you can see it doesn't say those words, and it's formatted a little differently, still relatively simple. Again, we'll go over the styling later on, but you can see really the only difference between this and what you had was just this project here, and this is the unique identifier. It's not a secret, so this can be embedded in your front end, but this is what identifies the project. This is what associates your Descope React components and all of those, all of the SDK components with this specific project and how you've configured your flow, and the flow itself looks something like this.

So, hopefully, you guys can see that it's not too small, but, essentially, this is the end to start to finish of how your authentication works. So, at the beginning, we have a welcome screen. We have a continue with email and a Google or Microsoft button here, and then if you click on one of those Google or Microsoft buttons, it actually performs a lot of authentication, provides you with the prompt to sign in with Google or Microsoft, does all that in the popup, and then after that, it just ends the flow and you've been authenticated. Otherwise, if you want to continue with email and you put in an email address and you click that button, then it will just sign you up or sign up or in with email. It will send an OTP to your email. If you're a new user, it will actually create a new user in the users management here, which I'll actually show you in a little bit. If you're an existing user, it also provides an OTP, but it just ends the flow afterwards. It doesn't update your user. And then what I can do is I can show you guys here. These are a bunch of different users, but you can see here, this is my specific user, and this is the login ID, which is associated with our OAuth login. So if I go to getting started and I click on sign in with Google, so since I'm not an incognito, and I'm already signed in with Google here, if I click that, you see it'll take me to sign in with Google. And this is what's actually going to go in our application. And then we see the session JWT, refresh JWT. This is the JWT that's actually this is the access. This is basically our session token that actually validates that we have a session and that we are authenticated. This right here is just the base 64 decoded session JWT here.

4. Using React Hooks and Dscope Provider

Short description:

In this section, we will learn how to use our React Hooks and implement the code in an application. We will clone the repository and explore the client and server folders. The app.jsx file should not contain any references to Dscope. We will install the required packages and obtain the project ID. Then, we will wrap the entire application with the Dscope provider using the project ID. This will associate our login page with the Dscope product we're using.

So it shows the claims as well as the headers. And then what we're going to do is we're going to use all this code. And we're actually going to we're actually going to put this all in an application. And I'm going to show you guys how to use our React Hooks and everything.

So let's actually start into that now. So if you head on over to this, if you haven't already had one over to this website, get the branch that we're going to be working out of unfinished. And you want to clone this repository here. And then I'm going to go over to VS code and actually show you guys what that looks like. So once you've once it's cloned. You can see here, there's a there's a full there's a client folder. There's a server folder. And then this is where the readme goes and everything. If you want to, at home, if you want to like, go over this, maybe go over the recording and follow along with me later, you can actually I provided the sign up or inflow that we use. And so I'll show you guys at the end how you can you how you can upload that in your own VSCO account and you can and you can play around with it yourself.

But here, so we have the we have the client server actually working out of the client first. So once it's been cloned you should be in a zero to off the root directory here with the client server. And I've actually provided some I provided some some scripts in the, in the package that Jason that will allow you to run the server and client very, very easily. You won't have to feed me into anything. But for now, you can see in client here what I what you want to do is you're gonna want to open up. Are your app dot JSX file and then actually this is what it should look like. Um, it should look like just very simple app dot JSX with no, with no mention of D scope at all. Um, D scope is this entire application has had D scope should should have to go completely removed from it. So we're gonna do everything ourselves and I'm gonna show you guys how easy it is to use our SDK. Um, but we have here are zero to off this is just a terminal window here. Um, what we wanna do is, uh, we want to 1st before we before we start, uh, kind of copying code over from the getting started with her. Uh, we want to use an PM install. This is going to install all the, um. All of the packages that we've, uh, that we've laid out in our package page on a package lock. Um, so let's let that finish and then. And then 1 more thing, um, I want to provide you guys with the project ID that we're going to be using. So, I'm going to paste this in the, I was planned and pacing this in the. So, right here I'm gonna send this to everyone in the meeting. This is the project ID hold on to this for now. We're gonna use this very shortly. But this is going to initialize our off provide. So, in the main app dot JSX and let's wait for this to finish, we can go back to forgetting started wizard. So, this, the way that this, the way that we've set up this react application, um, we want to have the offer, but we want to wrap the entire application in this provider. Um, uh, react, SDK, uh, wrapper here with our project ID. This will associate our disk login page, our actual, or this, this will sit here, our actual login page with the product that we're using. And so, um, and so we're going to use. This particular project ID, and the reason why you will probably see some different is because this is, this is tied to my specific project that I've set up for this demo. Um, your product will be something different. Um, but for, uh, it'll be easier for you to follow me if you use the one that I presented. So let's just, uh, let's just use that. And in fact, I can copy this whole thing for you guys and paste it. And if you, if you would like, so let's do that. So if you're familiar with react, this is the react wrapper. You can put it right here after though. Uh, we're going to place it in our app dot JSX right here and actually wrap the entire application. And then I have, uh, and then you could indent these, or I have, uh, I have a prettier and auto indent in there.

5. Running the Application and Overview

Short description:

We import the auth provider and wrap our entire application with it. After installing everything, we run the server and client. The application is a revenue dashboard with hard-coded data on the server side. It includes specific routes in Express and a login button.

Um, so it will automatically do that. It's just in my editor. Um, see if this is okay. Not sure what. Going on there. Um, but anyway, this is our, this is our auth provider, uh, this is our auth provider wrapper. We also want to import it here so that we don't get any errors off provider from. At DSCOPE react SDK. So this should, this react SDK should be installed through our NPMI. It's part of our package dot JSON. And then our auth provider here. Um, if you, if we actually run the application, it will, it shouldn't give any errors. Uh, if, if we've imported here, but let me just, let me start this real quick. I apologize going on there. Yeah. Okay. It's working now. Uh, maybe my editor's just a little wonky today. Um, but anyway, so we have, yeah, so now it says all of the packages have been installed and everything. Hopefully that was a little bit more, uh, seamless for you guys. Um, but, uh, basically all I've done so far as far as actually adding anything to this class, this project is import auth provider. And, um, and wrap our entire application with this off provider. Um, uh, hopefully, hopefully a softball or Chris can help you out if you're, if you're a confused about that. And I pasted this in the, uh, in the chat. So, um, what I want to do is actually, I want to actually run this application. I want to show you guys what it looks like. Um, so the first thing I want to do is, the first thing I'm going to do is after I've installed everything. Is I'm going to open up a second terminal window. You've seen you've done that here. And the reason why is because I want to run the client and run the server. So the first thing you want to do is run the server and you can do that by doing NPM run server. So you can see here, I have this script CD server. He has no DSM index. Yes. So the facts will run the server for us. Server is located here. And then, um, and then I'm going to go to the second terminal window. And I'm going to do NPM run. So that will actually serve already running client will run. Uh, and then take a look. Perfect. Okay. So this is our application. This is, uh, this is a, uh, this is, uh, a revenue dashboard. So it shows revenue information here. Um, I'll show you where it's getting all this data. We just have it hard coded on the server side. Um, but basically we have, uh, this is we click on each of these, these are specific routes and express. Um, these are specific routes and express that will, uh, provide us this information, return it in response. We have here, um, a log-in button.

6. Dynamic Login and Sign-in Page Integration

Short description:

We're going to make the login dynamic and change it to logout based on user authentication. We'll show you how to do this and how it can be applied to various applications. When we click on login, it redirects to the sign-in page, which is currently not available. However, by using the off provider, we can seamlessly add the sign-in page without affecting authentication or data protection. The login page is a react component that can be easily integrated. Simply copy and paste the disco low ID, which is associated with the project, into the login page. This ID can be obtained from the getting started wizard or the repository. After adding the login page, we can see it in the client and the console will display the user's name and email. To redirect back to the homepage, we remove the on success callback function and replace it with an arrow function that navigates to the dashboard.

We're also going to change this. We're also going to make this dynamic eventually and use our is authenticated react up to, um, to actually change that from login to log out, depending on if you're actually authenticated or not. So I'm going to show you how to do that. And you can, there's obviously a wide variety of applications with that in your own apps, your own projects.

But if we click on login, it's, it redirects me to sign in. Um, and we don't have a sign in page. So, um, and so what I want to do is the reason why we started with off provider is, uh, now that this is, you know, our entire application provider, we can just add the sign in page really seamlessly. Um, don't not going to actually do anything as far as like authenticating the use, or it's going to actually authenticate the user and create a job, but it's not going to actually affect our ability to see any information or protect any data because we still have to build out the middleware or the backend side. Um, but on the sign in page, if we go to sign in that JSX, which is located under off sign in. You can see here, this is our actual, this is our styling. And, uh, we have a row here. I've defined this here. So the total center in the spring. And so between these days, all we have to do is actually first thing, uh, first thing is import disco from at Cisco reactive decay. I'll do that real quick. Um, I believe in the repository that you're working with. Uh, you will need to do this. So right there. Good. Um, this is our, this is our, this is the actual, uh, react component for the login page. And what you can do is you can actually see that here. This is what we're just going to paste them. So you can see, uh, you go, and then the disco low ID, that is just this particular ID, which ties to the flow that we, that I've built here for everyone to use. Um, so remember we have our project ID already associated with the project. So all we need to do is just copy this in here, take that. And then we have to, we can just paste it in here so you can actually, this should be the same for any for, if you guys have the getting started wizard set up, you can copy and paste this. Cause we have our different projects. Have you already in there? So it's totally fine to do this. I'm also in case you close the getting started wizard. I will post that we'll paste this in the chat as well. Um, but this is just our login page. And, um, and as you can see, uh, because I'm already running the client, if I go back here, our login page is here and that's the same login page that we were seeing in the getting started wizard at the end, or at least on my getting started wizard.

Um, and so, um, and so if we. Open up the console here, login. Oh, look, it says, Kevin gal, Kevin. He's got.com. Now the issue is. It's not redirecting back to the homepage and it's just outputting in the console, my name and my email. And the reason why is because we have this on success here that just console logs, the name and email from the user detail. So what we want to do is we want to actually, I've already taken the livery of coping out this callback function that, uh, that is on success callback function that will navigate back to the dashboard, which is where all that, uh, which is where all that cool revenue dashboard stuff with. So all we have to do is just, let's just remove this on success. And then all we're going to do is we're just going to, um, just say on success. Oh, sorry. Hold on one more second. We need to no arrow function because we're already defining it here. We just say perfect. So now if I log in again. I refresh the page, go to sign in. And then I say, okay, sign up with Google. Go to discou.com goes back to that.

7. Adding Logout Functionality and Updating Popover

Short description:

We have completed the authentication flow and obtained session refreshed tokens. We haven't implemented sending the tokens with requests yet. We added a sign-in page that can be accessed at localhost:3000/sign-in. The dashboard still shows 'log in' because we haven't used the 'isAuthenticated' react hook to check if the user is authenticated. We want to allow the user to log out, so we'll add functionality for that. We'll use the 'useDisco' function from 'he's go react to stk' to implement the logout function. The logout function will invalidate the user's session. We'll create a 'logout' const and initialize it with 'useDisco'. When the user clicks the logout button, the function will be called to invalidate the session. We'll also update the login/logout popover to show the appropriate content based on the user's authentication status. To do this, we'll use the 'isAuthenticated' react hook and display the login or logout popover accordingly. We'll import 'newSession' to associate and retrieve current session information.

Great. So we know the flow is completed. You can actually see, um, you can actually see here we have our, uh, DS and DSR. These are our session refreshed tokens here. So, um, this is already, this is already, we already have authentication. Um, and, um, and, uh, we're not doing, we're not actually sending this with any of the requests yet or anything like that. We're still going to code all that. But, uh, pretty straightforward. But I mean, you could see in maybe, you know, a few minutes we added, uh, we added a sign in page and you can just, you can always view that by just going to, uh, local host 3000 dash sign in, you can see that sign in page. Now, if you go back to the dashboard here, you'll see that it still says log in. The reason why is because we have encoded, we haven't used the is authenticated react hook that can determine, and you can embed these in anywhere, in any react, um, in any part of your react application to check whether or not if you want to perform some logic to check whether or not the, uh, the user's authenticated. So, um, the first step we want to do is, uh, we want to actually allow the user to log out. We want to happen. Not only do we want to say log out, we want to actually have that functionality. Um, so let's go to nav bar, which is under, uh, which is under components editor nav bar dot JSX. And as you can see here, um, I have a few things already coded out that aren't being used. So we have a log out user and log in user callback function. Um, we have a log out pop over in a login pop over the only difference between these two is that the color is different. One says log out once it's log in. You'll see those working in a minute. And then on click it points to a different function. Now, the reason why that is, is because when we log in, all we want to do is go back to the sign in page. But when we log out, we want to also go back to the sign in page, but we want to first log out and we do that with the discovestigate. So what you want to do is you want to import, use disco. From. He's go react to stk. Hopefully this is making sense to you guys. I'm just going to import this. And then this is how we're actually going to, this is, this is, uh, this, our login there's our, sorry, our logout function is baked as part of, is baked in a part of this use disco. So if we go to con, if we create a const logout and initialize it with. Use disco. Now we have a log at, we have an eight. We have a logout function, which we can use. We can, uh, we can use within a wait to actually log out the user and invalidate their seconds. Um, so I can explain a little bit more later on if we have time about how this works and how the technology can work with the dots, but for now, um, I'm just going to show you guys, so under logout using the, it's the same as login. The user, um, instead of it being exactly the same, we're just going to have a try catch and the try catch is going to log out the user. So, you know, we're going, we can just say console log error. If there is an error, but if there's no error, all I have to do is say, Oh, wait, logout. So now when the user, you know, when, when the user clicks the logout button, which we haven't actually embedded yet, but when the user clicks out the lock, and clicks logout button, it's going to run this real quick and just make sure to invalidate the session. You can see it's an async function here that will, um, that will make sure that the session got us invalidated. Um, and so, uh, so now you can see here we have a logout and login popover. These two I created here. What we want to do is right now, if you go scroll down to where the popover is defined here, login popover, you see, there's the content. It's only ever showing login. Right? Even if I'm logged in or logged out, it doesn't matter, and there's no logic behind that. So the way that we're going to do this is underneath, uh, underneath, uh, div class same, uh, avatar we are going to, uh, we're going to actually use one of our is authenticated react hooks and have a separate logic to either show the login or logout popover, depending on the user is authenticated. You'll see what that looks like in a second. First thing we got to do is underneath here. You want to actually, uh, actually before that, we want to import something called new session. This is how we're going to associate, uh, and, and get session information, current session information.

8. Handling User Authentication and Protecting Data

Short description:

We can determine if the user is authenticated and show different popovers accordingly. If the user is not authenticated, we show the login popover. If the user is already authenticated, we show the logout popover. By clicking the logout button, the user's session is invalidated. We need to protect the data by changing the way we send requests and including the session token in the authorization header. We also need to update the backend server to validate the session. In the dashboard.jsx file, we ensure that the server only returns data if the user is authenticated by including the authorization header in the Axios get request.

So this would show us if the user is authenticated, for example, and then we can say under log out, we can say, um, cons, uh, we can say, uh, actually before we do that, let's do. Yeah. It's a con. Yes. Perfect. So, um, so this is authenticated is it's, it's part of the disco react SDK, but this is initialized with new session. This will determine this current session information of the user, whether or not they're logged in or not. Um, and so what we can do is if we go back down to the pop-over here, all I need to do is say, uh, if they are not authenticated this year, underneath pop-over. You can see if it is not, if the user is not authenticated, it's going to show this login pop-over and, um, and which makes sense, right? If they're not, if they're not logged in, we want to give them the option to log in and show this green login button. However, if they are already authenticated. So if we're going to say if it's authenticated as true, basically. Then just copy this code. You can copy this code. Um, and the only thing we're going to change is instead of the concept being logged in for pop-over, we can say it's log out pop-over. So now if we go back to our application, hopefully this made sense to you guys. Well, we're doing, um, but basically now it's going to show two different pop overs, depending on what we are. And you see, because we're already logged in, right. We logged in before. Now it's showing log out instead of login. And if I click this, it's actually going to log the user app. So now the session is invalidated. And if I go back to the dashboard and I click here, you see it says log in, right, because we already logged out the user and the session's invalidated. So we can, so that use session is returning to its authenticated fault. Um, and you can see here, we're still seeing this data. So this is a problem, right? We don't want to show this data. The whole point of, of doing this is we want to eventually protect this data. Um, uh, and so there's two components of this. We have to first change the way that we're sending the request. We have to include in the HTTP header, uh, off in the authorization header, uh, bear, and then the session token, which we're going to get from the react SDK. And then we also have to change the back end of the node JS. Uh, server that we're running to actually, uh, make sure that the session is, is valid. Um, so we're going to do both of those. Let's, uh, let's just finish up with the front end real quick. So if you head over to dashboard.jsx, which is under dashboard component or actually, sorry, just dashboard and then dashboard.jsx. Um, you can see here, this is the dashboard. This is the, this is the main, uh, main dashboard you're seeing right here, and then, um, I've coded out a lot of, uh, I put out a few things already, uh, specifically if you notice this open notification icon, don't worry too much about what that is, basically. Um, I just have it so that, uh, if the user is, uh, if the user attempts to make a request, it will, it will display an error message and then automatically redirect them back to, uh, back to the login page. Um, but right here you can see, you know, navigate with sign in. That's the callback function we're using. That's not super important. What is important is this. So every time I'll show you guys, every time I click on one of these. Open up network real quick. I'm getting a 200 and then it's sending a request out to local host 80. That's where service has been bar chart and it's returning, it's getting back all of this information that then react processes and displays in that fancy. So what we want to do is we want to make sure this doesn't come back from the server unless the user is authenticated. Of course. So, um, so you can see here, uh, there are currently. No authorization headers. Um, so we want to include that in our Axios, uh, uh, get requests right here.

9. Configuring HTTP Header and Session Token

Short description:

In Axios, we configure the HTTP header to include the authorization header with the bearer session token. To get the session token, we use the Dscope React SDK's get session token function. We define the session token within a try block and include it in every get request with the bearer token in the HTTP header. When logged out, the bearer token is empty, but when logged in, it contains the session token. This allows the backend to verify and process the request.

So under this is the, this is if you're familiar with Axios, we actually have, I'll show you guys, we have a second validation, um, section of our docs that show how it's used with fetch, but if you're familiar with Axios, this is where you'd actually configure the HTTP header. So what we can do is we can say headers. And then another thing right here, and if we could say authorization, because we want to include authorization headers and then bearer session token. So what I'm doing here is I'm actually including in every single response. A authorization header in our HTTP header. That's bearer and then the session token. Thing is I have to define the session token, right? How do I get the session token after users been logged in? We do that with the Dscope React SDK. So up here, let's import, I believe it's get session token. Simple function that we can call and it'll return whatever the current session token is, if it's valid and if there is a valid session. So it'll return get session token here. And then underneath, we can underneath this try, when it's actually every time it's calling and making that request. We can define it here at session token equals get session token. Now, you can see here, it's getting the session token if it exists. From the, and it's in the try pack. So it's getting session token if it exists and then in every single get request that it makes for the permission it sends the session token with bearer in the base, in the HTTP header. And we can see that if we go here and we just refresh this page. So if I click this, You can see it says bearer and nothing. Now the reason why so are we actually logged out if you remember, and we don't have a valid session token, but if I log in, All this. But when you see this bearer and then this is the actual job that we're sending. So this is this is great this is what's going to allow this is what this is what no JS and our back end is going to take process and use and actually utilize to verify the second and either return information.

10. Node.js Middleware and Session Validation

Short description:

I've shown how to dynamically use is authenticated, add the sign-in page, and include the HTTP header with the session token. Now let's work on the Node.js middleware, the authentication middleware in our server. We need to design a middleware that validates the session before returning the response data. We'll build out this middleware and explain the concept in Express.

So we're almost done. I've shown you guys how to dynamically use is authenticated and different parts of application. I've shown you guys how to actually add the sign-in page. I've also shown you guys how to add the HTTP header with the session token and how to use the React SDK to do that.

Now let's wrap this up by working on the Node.js middleware, the authentication middleware in our server. So this is all great. Now what we want to do is we want to click out a client and we went ahead to server index. Yes, so this is our actual Express server and go over this earlier. But if you're familiar with Express, here's where it's being initialized. And then this is the actual port that's running on 8080.

And then here, app.listen is where the server actually starts and where it listens for a request on that particular port. And here are all the routes that are defined, we're using a prep router. And then these are all of the, like the bar chart, for example, I showed you guys earlier, this is where it's sending the information in the response. This information here is actually defined as just based on data based like hard coded into a TypeScript file here under data. This is the information that you were seeing from the API response. And then another thing to note is this Auth Helper which I've also created. This is relatively simple and I'm gonna get into how this works, but this is what we're gonna use to actually see the request authorization header from each of our routes.

So, first thing we gotta do is if we want to validate the session, we want to design a middleware that rests between our request and our response. So when the request comes in for each of these routes, we want to first use like under router here, we want to say router.use some off middleware. And that will make sure that the middleware validates the session before it returns the response data. That's just a concept in Express. And it's going to basically come here and then call the next function. So, we actually need to build out this middleware. This middleware, we have code snippets available on our docs, but I'm going to show you guys a simple way to build this out right now.

11. Building the Session Validation Middleware

Short description:

This function takes in a request, checks for authorization headers, and returns the token if available. We need to design a middleware to validate the session between the request and response. We instantiate the G-scope clients with the project ID and define the off-middleware. We run a try-catch block, await the validateSession function, and return a 401 Unauthorized response if the session is invalid. We get the session token from the request using the getToken function from Auth Helpers.

So this is the function I was showing you earlier. This is what's actually going to, you can see this, it's going to actually take in a request. See if there are any authorization headers available. If there aren't, then it's just going to return an empty string. And then the validate session will fail, and otherwise, it's going to return whatever the actual token is after bear. That's the split and why it's split based on the empty string.

So, first thing we gotta do is if we want to validate the session, we want to design a middleware that rests between our request and our response. So when the request comes in for each of these routes, we want to first use like under router here, we want to say router.use some off middleware. And that will make sure that the middleware validates the session before it returns the response data. That's just a concept in Express. And it's going to basically come here and then call the next function. So, we actually need to build out this middleware. This middleware, we have code snippets available on our docs, but I'm going to show you guys a simple way to build this out right now. First thing we have to do though is we have to actually instantiate our G-scope clients. And we do that with our project ID. So, I gave you guys this. We're going to use the project ID that I gave. So, if you go back to your after.jsx file, you can copy it over from here and off provider. This is again, this is how your project and G-scope, how you configure your flows is associated with your Node.js and your React project locally and in production. So, this again, this is not a secret. You don't have to worry about this being exposed. There's no information that can be taken from this or secure information. But basically, I'm defining it here so that we can then use the validate session function, which is a function as part of G-scope client that will allow us to just pass in that session token and return a promise true, basically, if it works or not. And so, I'm gonna define this off-middleware here. That's actually what's going to do that. And then, because I'm using TypeScript, I have to actually define the types. But what I'm gonna do is I'm just gonna say request, request, respond, respond, and then next function, boom. And then, here, we are passing in the request, respond, and next function. And we're going to actually just run a try catch. Again, just like kind of how we were doing it with the log out. So, we're gonna say try catch, and then say E. And then all we're gonna do is just await ClientsAuth.validateSession. And then, the session will actually come in. The session token will pass in there, and then it will either say, okay, it's a valid session, continue, or not. So, if it's not a valid session, what we want to do is we probably want to return some kind of response HTTP status code. So, we'll do res.status 401, unauthorized. And then, we can say here, JSON, we can say error, new error. And then we can say. Oh, sorry, not here, not here. One thing to note here is, oh, because we're using an await, let's also make this an async function here. So, we get rid of this error here. And then client auth.validate session, we actually need to pass in the session token, right? We need to get that session token. And how we're going to get that session token is, if you remember, it was passed in through each of the requests here. Bearer session token. So, how we're going to take that is, we're going to call our get token function, which was in the Auth Helpers, that's what we imported earlier. And, remember, you can see it takes in a request. And we're just going to pass in the request. So, if we pass in the request, it's going to go here, it's going to actually get the authorization header, and then it's going to just validate the session and see if it works. Now, if it returns a 401 Unauthorized, we'll just have it return. I'm not going to do anything.

12. Testing Session Validation and Conclusion

Short description:

Now, if it works, because we're using Express, we can just say next, and then it's just going to call each of these and actually return the information that we want. Let's test this out. When I call one of these, it says 'log out', so that means there's a valid session. I'm getting a 200. If I log out and go back to the dashboard, it says 'unauthorized, redirect to sign-in page'. If we sign in now, we have a new session token. That's basically it. For more information about session validation, you can visit the provided website. Thank you everyone for joining.

Now, if it works, because we're using Express, we can just say next, and then it's just going to call each of these and actually return the information that we want. So, let's test this out. We're actually, we're already using this right here in Auth Middleware, where we started earlier. So now, when I actually call one of these, let's refresh the page. You can see it says, log out, so that means there's a valid session. I can see the information. I'm getting a 200. Now, if I log out, and I just go back to the dashboard, oh wait, hold on, sorry. Yeah, I can log in. Oh, I'm sorry. I have to restart my server. Because it's not like React. Okay, my bad. So let me reset the server, because now we gotta apply all these changes we did to the server. And now, if I go here, it says, unauthorized, redirect to sign-in page. So, and then it should automatically, it should automatically redirect us to the sign-in page. So you can see here, it automatically redirects. Let's just go back and verify one more time. So if we go to market breakdown, you can see nothing shows up, and it takes us back to sign-in page. Now if you sign in. So if we sign in now, we have a new, we go to network, we have a new session token. So if I click on this, you can see it shows up now, and that's because we have our valid session token right here. So, and you can see logout there. If we go back to and if we can do one more request here and I can show you what it looks like because it should just return a string, but you see right here, our 401 unauthorized here, it just returns bare empty string. Because in our, in our ELF helpers, it just returned empty string after bare. Cool. Great, so that's basically it. That's basically it. Let me go, let me show you real quick what, how the, how we have our docs here for doing the session validation. So if you can see here, this is how we actually send a session token to the app server. Here it's using set I use Axios, but it's the same kind of idea. We're doing bare plus session token. So we did that. When we did the session validation with the back end, we actually use, we instantiated a Dscope client here with a project ID. And then we validated the session doing .validate session. I forgot to mention I actually, if you go here, you could have, we could have actually just copied this also from directly from the getting started wizard. So that's another easy way to do it. But if you want to learn more about how to validate session, how the different ways you can, you can do it with different frameworks and languages, you can, you can go to this website here. It will show you a, I will post this in the chat. Yep. And then finally there's some more information about specific middleware. Like if you want to use, if you want to use cookies instead of what I was doing, you can, you can look at, you can search middleware here or any other session validation functions. All the functions that are part of the Dscope client, the Dscope client object that we initialized with our Project ID here, all the built in functions are listed in the, in the readme. So I also provide that here. Any, I guess I'll just open up. We have, we only have four minutes left, but if you guys have any questions that were unanswered, I'm happy to answer them. You can ask them in the chat or you can, or you can talk. Yeah. All right, well, thank you everyone for joining.

13. Customizing Flows in the Dscope Console

Short description:

I'll show you how to customize the flows in the Dscope console. You can add different elements like a phone number or email. By dragging and dropping components, you can easily create an email authentication flow. The React component will automatically update in your application. You can also customize the look and feel of your app, including colors and logo.

All right, well, thank you everyone for joining. I hope that was informative. And I hope you guys can see how easy it is to utilize a lot of these SDKs we have and customize your flows.

Oh, one more thing. I'll actually show you guys, I'll actually show you guys real quick how you can actually customize this. So here, for example, if you go into the flows and you actually want to, for those of you who stayed late, you can, you get to see this. We can actually, you can actually add whatever you want. If you want to add something, if you want to add, let's say, like a phone number or something like that, you can add that in here. And then, and then you can see if you want to, we can do something like this. Actually, before, actually, I don't wanna mess with this flow. Let's go to, let's go to like Spinoff, for example.

Cool. So, if you wanted to add email, for example, you can paste in email and then you can put in a button here and then you can see, I'll make this a little bit bigger, you can actually see there's a new Click Me. And then what you can do is you can go to Action, you can add no TP email signup or in here, drag that in there and then drag, it's a little hard to see probably for you guys, but you can just drag this to the end after it's verified the OTP, so now you have, so now you basically just, in like literally 10 seconds, add an email, email TP authentication to your app and this will automatically, because you're using our React component, will automatically update itself in your React application and then you can even change your, you can change like the look of everything, you can change the colors, you can go into styles here and actually change your logo and primary, secondary colors and how errors are displayed and everything like that, so, pretty cool. But yeah, thank you guys for joining and hopefully see you again soon.

Watch more workshops on topic

React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Featured WorkshopFree
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
React Advanced Conference 2021React Advanced Conference 2021
132 min
Concurrent Rendering Adventures in React 18
Featured WorkshopFree
With the release of React 18 we finally get the long awaited concurrent rendering. But how is that going to affect your application? What are the benefits of concurrent rendering in React? What do you need to do to switch to concurrent rendering when you upgrade to React 18? And what if you don’t want or can’t use concurrent rendering yet?

There are some behavior changes you need to be aware of! In this workshop we will cover all of those subjects and more.

Join me with your laptop in this interactive workshop. You will see how easy it is to switch to concurrent rendering in your React application. You will learn all about concurrent rendering, SuspenseList, the startTransition API and more.
React Summit Remote Edition 2021React Summit Remote Edition 2021
177 min
React Hooks Tips Only the Pros Know
Featured Workshop
The addition of the hooks API to React was quite a major change. Before hooks most components had to be class based. Now, with hooks, these are often much simpler functional components. Hooks can be really simple to use. Almost deceptively simple. Because there are still plenty of ways you can mess up with hooks. And it often turns out there are many ways where you can improve your components a better understanding of how each React hook can be used.You will learn all about the pros and cons of the various hooks. You will learn when to use useState() versus useReducer(). We will look at using useContext() efficiently. You will see when to use useLayoutEffect() and when useEffect() is better.
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Featured WorkshopFree
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
React Advanced Conference 2021React Advanced Conference 2021
145 min
Web3 Workshop - Building Your First Dapp
Featured WorkshopFree
In this workshop, you'll learn how to build your first full stack dapp on the Ethereum blockchain, reading and writing data to the network, and connecting a front end application to the contract you've deployed. By the end of the workshop, you'll understand how to set up a full stack development environment, run a local node, and interact with any smart contract using React, HardHat, and Ethers.js.
React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Featured Workshop
React Testing Library is a great framework for React component tests because there are a lot of questions it answers for you, so you don’t need to worry about those questions. But that doesn’t mean testing is easy. There are still a lot of questions you have to figure out for yourself: How many component tests should you write vs end-to-end tests or lower-level unit tests? How can you test a certain line of code that is tricky to test? And what in the world are you supposed to do about that persistent act() warning?
In this three-hour workshop we’ll introduce React Testing Library along with a mental model for how to think about designing your component tests. This mental model will help you see how to test each bit of logic, whether or not to mock dependencies, and will help improve the design of your components. You’ll walk away with the tools, techniques, and principles you need to implement low-cost, high-value component tests.
Table of contents- The different kinds of React application tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting DOM elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RTL tests and how to handle them
Prerequisites- Familiarity with building applications with React- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Testing Library- Machine setup: Node LTS, Yarn

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

React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
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!
React Advanced Conference 2021React Advanced Conference 2021
39 min
Don't Solve Problems, Eliminate Them
Humans are natural problem solvers and we're good enough at it that we've survived over the centuries and become the dominant species of the planet. Because we're so good at it, we sometimes become problem seekers too–looking for problems we can solve. Those who most successfully accomplish their goals are the problem eliminators. Let's talk about the distinction between solving and eliminating problems with examples from inside and outside the coding world.
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Can useEffect affect your codebase negatively? From fetching data to fighting with imperative APIs, side effects are one of the biggest sources of frustration in web app development. And let’s be honest, putting everything in useEffect hooks doesn’t help much. In this talk, we'll demystify the useEffect hook and get a better understanding of when (and when not) to use it, as well as discover how declarative effects can make effect management more maintainable in even the most complex React apps.
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
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.