JWT Authentication for React and FastAPI (easy with code)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
check this out I type in coding with Robi password Press login and boom we're in hey friends in this video we will create a simple react application along with a simple fast API application we will create authentication using jwt's on the fast API side along with having a user SQL database and on the react side we'll create a simple login page that when a user is authenticated it redirects the user to a new protected component all right so we are going to set up Authentication for fast API and a react front-end application now how I start this already is I already have a virtual EnV which is a virtual environment and I have this requirements. text for our fast API so I'm going to start by just saying pip install - R requirements. Tex all right so this installs all the dependencies that we need for fast API now the very first thing we can do is go in here and let's go ahead and create a database. py file and then inside our database. py file we want to say from SQL Alchemy we want to be able to create our engine we want to be able to create a declarative base and then our session maker for this tutorial I'm going to be using SQL light because it's just so fast and so easy and so awesome to use for these kind of tutorials now the next thing we're going to do is create a new file called models.py where we can say what our models or database tables are going to be inside our database so we're going to create a new class of user user which has an ID a username and a hashed password now something about authentication is inside our database we never want to save the password as plain text we only want to be able to save the password as a hashed password which means we're using some kind of like bcrypt algorithm to be able to Hash the password and then when a user tries to log in we'll hash that password and see if they equal the exact same you can't unhash a password once you hash it you can only hash it and you can verify if they're the same unique characters all right now let's go back into our backend and let's create a main.py file and now as you know I start pretty much every tutorial by just going through our fast API application where we're going to have a bunch of dependencies for pantic password hashing and encrypting jwt's CU we're going to be using jwt's for this and then our database in fast API with SQL Alchemy now to get this started we need to create an oof2 scheme which equals our oof2 password bear with our token URL of token this is where we're going to be able to identify where the JWT is in our code we now have to do a little bit of cores control which means we can't have outside applications hitting our fast API application without us saying hey this application is all low to call our endpoints it's a way to just protect us from outside users now I inside here have our origin equal to our Local Host Port 3000 that's going to be the main development URL for a react application I added added this in here just in case you want to use it in the future this could be your production server so if you deployed your react application you would want to add that URL here we're then adding a middleware inside our fast API application which takes in our Kors middleware and then we are allowing certain things so really here we're allowing all types of requests but we have to say hey if it's from this origin we are allowing all types of requests if it's not from this origin we're going to deny it completely and throw a chord error and again the cor's error is to protect us from outside users next we want to be able to create our database dependency for our yield and then we want to create our password context which is going to be schemes bcrypt with deprecated Auto this is a way for us to be able to Hash our passwords in the future we need to create a secret key for our JWT for this tutorial I'm just going to use your secret key but you'll want to make this Secret in potentially using something that's like creating characters automatically we're going to be using the hs256 algorithm and it expires in 30 minutes now the very first thing we're going to be doing is making it so we can create users in our application so we're going to create a new class of user create which takes in a base model with a user name and password and then let's allow the user to be able to create a new user based on this create user call and what we're doing here is we are saying when this create user gets called we're going to create a DB session we're going to create a user create and then we're going to have our hashed password which uses that password context up here where we're hashing our user password and then saving that user to our database and then returning complete now to be able to call this we need a API endpoint with a postregister where we're creating a user dependency and a user create where a DB user is get user by username if that user is null well then we're going to create the user if the user does exist we're we going to throw a HTTP exception saying that user is already registered now we want to authenticate the user by throwing a user query to check if that user is verified or not and then if not password contacts verify that user create the access token based on dictionary we want to create a new post for our token and then a verify token and then our get verified token where we're using to verify the user now if you want to go in detail with this I have another video on Fast API jws I'll post that video right here but for the time being I'm going to take it that you kind of know what's going on with jbts in fast API all right so now that we have our backend all configured let's go into our front end and I'm going to create a new terminal so this first terminal is going to be for our back end and then I'm going to create a new one for our front end so we can just say CD into our front end now the very first thing we need to do here is create our react application now this this tutorial is assuming you have like nodejs 18 or higher I think that's what I have installed on my machine right now so you need to be able to run an MPX create react app this last off app is the name of the react application I'm creating now once you type that in this will install all the dependencies that we need for our react application I'm going to close these fast API files so it doesn't get confusing we are no longer in our backend directory we are in our front end directory now once you are inside your frontend directory we need to CD into our off app and then here we can do an mpm install react router domum this will install all the dependencies that we need to be able to use routes and links inside react now the very first thing we want to do is go into source and let's create a new component called login.js inside here we want to add quite a bit of stuff we want to add a react use react inside our react and then we want to use navigate from our react router Dom we want to create a function of login which holds a bunch of pieces of state so username password error and loading we want to instantiate our use navigate from react router we want to be able to validate our form by passing in a username and password for our username and password are required fields we want to be able to handle our submit so once a user tries to log in we want to be able to handle those submissions we have our form details with URL search prams where we pass in our form details of username and password we want to then try and call our await fetch for our token where we can pass in post and our content type is going to be application /x www form URL encoded with our form details which is going to be our username and password if we get a successful response we're going to be taken to a protected component that makes sure you have a token valid but before we do that we set our local storage which is a way for us to be able to save information on our browser we set our local storage to whatever the token is that we get back once we try to log in as a user if there's any issues we'll throw an authentication failed and then we'll catch the eror and then right here we just have a form that is a login password and then if there's an error we'll print the error in red let's now create a new component called protected. JS and inside here we have our react use effect with our react and our react router now what's different about this page is the very first thing we do here is we verify our token so we check to see what our token is inside our local storage.it item token I'm printing our token right now you can delete that if you would like and then we have our const response equals a weight fetch which is our token path to verify our token if it fails we navigate back to the normal slash which we're going to set up as our login page and if it all works we are going to say this is protected path only visible to authenticated users now let's go inside our app.js and let's swap this all out with our browser router as router routes and route from our react router Dom where we have a login page component and our protected page component now let's see what happens let's start by turning on our database and we can do this by doing a uicorn main colon app-- reload and then inside here we can go to our mpm start this will start our react application now before we do that let's go into our fast API docs and let's register a user really quick I'm going to register coding with Robi and the password is going to be abc123 and if we execute this we can see that we got a successful 200 complete response from our fast API application now if we go into our react app we can try and log in so I'm going to say test test if we try and log in with this user we're going to get an incorrect username or password and now if we go ahead and type in coding with Roby with the password abc123 and we click login we can see that it's going to tell us this is a protected page only visible to authenticated us users now how is this working well if we go and right click and we go to inspect into our Dev console and we go all the way over to application we can see inside our local storage we are saving a token and this token is a valid JWT that was given to us from our fast API application now there's a couple ways for this to fail if this token is wrong or it is expired we can go in inside our protected JS and see that if there is an error we remove it completely so let's go ahead and say we wanted to modify this and then we wanted to refresh we can see that it deletes the token because the verification failed and it brought us back into our username and password if we tried to go back to our protected path it's going to reroute us back to the login if we go back into coding with Robi and we type in abc123 and we log in another thing that we can do is go ahead and just rightclick on this token delete it and if we refresh it's going to bring us back so this is how you can Implement react authentication using fast API pretty simple using jwt's if you want this code I'm going to leave it in the bio below and I hope you enjoyed this video
Info
Channel: Eric Roby
Views: 4,728
Rating: undefined out of 5
Keywords: fastapi, fastapi python, react, jwt, fastapi jwt, fastapi tutorial, fastapi react auth
Id: YpvcqxYiyNE
Channel Id: undefined
Length: 11min 51sec (711 seconds)
Published: Wed Apr 24 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.