Fullstack App with Session-Based Auth in Django & React.js (Vite) #django #react #vite

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's going on everyone this is Amir from be bra's Channel long time no see hope you're all doing well in today's video actually we're going to look at how to authenticate single page applications with session based authentication we'll be using D Jango obviously for our back end while the front end will be built with reactjs reactjs of course is a famous JavaScript library designed for building user interfaces but you know that already and before we get started and get to the interesting part of coding our application today let's talk a little bit about the main differences between session based off and token based off so with the session based authentication a session is generated and the ID is stored in a cookie and you can see here on the screen you have on the left side the client and on the right side the server you get the HTTP post to log in with credentials that go to the server so after logging in the server validates the credentials and if valid it generates a session stores it and then sends the session ID back to the browser now the browser stores the session ID as a cookie which gets sent any time a request is made to the server also it's important to note here that the session based off is St ful which means that each time a client requests the server the server must locate the session in memory in order to tie the session ID back to the associated user on the other hand we have the token based off the token based off is relatively new compared to session based authentication and it gained really traction with the rise of the spas and restful apis so again you have on the left side the client and on the right side the server and and the first step is the same the HTTP post is sent to login with credentials and after logging in the server validates the credentials and if valid it creates and sends back a signed token to the browser in most cases the token is stored in local storage the client then adds the token to the header when a request is made to the server and assuming the request came from an authorized Source the server decodes the token and checks its validity so what is a token really a token is a string that encodes user information as you can see on the screen and we have here token header and token payload I've talked a lot about tokens when I've explained the jot or Json web tokens I have two different videos on jots one with flask and one with fast API I'm going to leave the links to those two videos in the description section Below in fact one great Advantage about using token based authentication is that token can can be verified and trusted because it's digitally signed using a secret key or you know public private key pair so the most common type as I said is Json web tokens or jots unlike session based off token based off is stateless not stateful since the token contains all information required for the server to verify a user's identity now let's talk a little bit about security vulnerabilities so as I mentioned session based off maintains the state of the client in a cookie while jots can be stored in local storage or cookie most docum based authentication implementations store the jot in local storage so both of these methods actually come with potential security issues like you can see on the screen so you have a cookie with the security vulnerability of cross-site request forgery or csrf so csrf in short is an attack against a web application in which the attacker attempts to trick an authenticated user into performing a malicious action so most CSR F attacks Target web applications that use cookie based off um since web browsers include all of the cookies associated with each request's particular domain so when a malicious request is made the attacker can easily make use of those stored cookies on the other hand for the local storage you get the crosss side scripting or the X SS and xss attacks simply are a type of injection where malicious scripts are injected into the client side and usually this is performed to bypass the browser's same origin policy so web apps that store tokens in local storage are open to xss attacks so open a browser and navigate to any site then open the console in the developer tools and type json. stringify local storage then press enter CER this should print the local storage elements in adjacent serialized form and yes it's that easy for a script to access local storage and we are almost there so all in all we're going to take a look at how to authenticate Spas with the session based authentication using D Jango for the back end and reactjs for the front end one more thing before we get started if you're new here thank you so much for coming in and stopping by uh feel free to subscribe to like any of the videos that you enjoy really and if you like my content don't forget to hit that notification Bell to get the latest tutorials crash courses and videos from our Channel and for those of you who have been supporting me for the last 3 years thank you so much for your support I appreciate your feedback suggestions and everything you do for the channel now with that out of the way let's roll up our sleeves and start creating our Dango project so let's go ahead and create our D Jango project but before that I want to create create a global folder so uh let me first go to my main folder all right and um let me create a folder I'm going to call it Jango react off create a folder I'm going to call it back end okay and then CD to back end and then I want to activate the uh virtual environment I use usually pnv so if you don't have pnv you can do pip install pnv sometimes they use poetry but I use pip so yeah either way it will work once you've installed pnv you can do pnv shell and this is going to um activate the virtual inv environment inside your backend project so all of the dependencies and packages that you're going to install are going to be installed only inside your backend project now let's go ahead and install Jango so again I'm going to use pnv install Jango all right perfect so uh let me just clear the terminal so what we'll do is Jango admin start project and I'm going to call our project D Jango cookie off okay so if you will uh write dur or LS uh you will find that we have here Jango cookie o so let's um change directory to that Jango cookie off and here I want to do python so and we have manage.py that's a very important file in order to create our application so to use it I'm going to type python manage.py start app and the name of the application I'm going to call it API okay perfect so now we have everything is set in order and let's go ahead and open our project using visual studio code you simply type code space dot so you will need to set it up in a way that code dot can open Visual Studio code um inside your current folder that you're opening your terminal all right so hit enter and we should see Visual Studio code opening okay and we have our Visual Studio code uh open in our folder so API that's our application D Jango cookie o that's our project so the first configuration step that we always need to do is to add the name of the application in installed apps here so you can do API simply or you can do api. apps. API config uh you can do both ways uh so that's the first thing so our application is going to have different API endpoints we will have login log out session and who am I button so first of all let me go to views.py me just close the Explorer and let me first import um Json which is Javascript object notation module of course that's used to encode and decode Json data also I want from uh Jango do contrib do o I want to import authenticate also I want the login and the log out next I want um from Jango oops Jango HTTP yep I want to import Json response also from D Jango do views. decorators do csrf so we want to ensure uh or we want to import ensure csrf cookie in a nutshell the first line here this from jango.com trip. off this line simply Imports those specific functions authenticate login and log out from the contri doof module uh these functions are used for handling user authentication and session management the next line line number six Imports the Json response class from the D Jango HTTP module next I want also to uh import from D Jango do views. decorator. HTTP I want to import require oops require post so I hope this is clear enough for you guys so I'm going to use it immediately actually uh this requir post decorator to create a function and I'm going to call it login underscore view to take as an input request so declaring a variable um called Data Json do loads request. body next I want the username and the password so the username data do get username and similarly for password password so what we have done here is that we have pared the Json data from the requests body so this simply is going to extract the username field from the Json data stored in data for both the username and the password um all right so next I want to um check out if the username and password fields are missing from the Json data and then return an error response if they are um potentially missing so to do that simply I'm going to say if username is none or password is none I'm going to uh return Json response here then and uh I want it in a form of Json so detail and the detail here will say please provide username and password now we're going to attempt now to authenticate the user by calling the authenticate function with the provided username and password so let me declare um user variable that's equal to and here we're going to authenticate and we're going to set the username uh equal to username and password equals to password next I want to check out if authentication fails um in other words user is none so if user is none I want to return Json response then we'll open curly braces we need it in a ad Json form so we'll say here invalid credentials and also I need the um HTTP status code to be set to 400 else the authentication is indeed successful and I'm going to pass the request and the user to the login uh method here all right so that's the um uh and also uh let's return adjacent response so return Json response we'll say here so this is uh detail and here let's say something like successfully logged in the second function is the log out view so log out view taking the request so here simply we want to ensure that only the authenticated users can log out so how to put it in code structure simply we can say if um not request. user do is authenticated in this case we want to return something like uh you are not logged in and also I want status to be 400 else we will log out indeed so log out and we will pass here uh the request and we will return G Json response uh something like um successfully logged out the following thing that we want to do is we want to take the ensure csrf cookie and we're going to use that function that uh decorator here and we're going to create the other two functions the session View and who am I view so the first function session underscore view that takes uh request as an input and then uh I want again to check out if the user is authenticated or not and the way to do that is simply we will say if not request. user do is authenticated in this case we will return uh Json response let's set the is authenticated to false otherwise we will return Json response and also the is authenticated to true the next function that I want is who am I view and that's also going to take request then again I'm going to check out if the uh user is not authenticated basically that's the same code so actually can do like that and do like this and be careful here because we don't want to set simply is authenticated to true but instead I want to set the username to request. user. username whatever the username of that authenticated person and that's it basically this is our views file now let's go ahead and open uh our application here I want to add urls.py file and we're going to define the following URL so first I want from uh Jango do URLs to import path next I want from the current directory to import views then we want the URL patterns so uh path say here login this comes from views. login View and name is login let me just minimize this a little bit and we need four of them so we want the log out we want the uh API session and I want the who am I session and who am I log out we have here log out view we have here session View and and finally we have the who am I view all right so this is our URLs file let's also go to URLs which is uh in our main project here so we are registering our um API URLs here to our base project here let me just add include as always so we will need here path uh a oops AP API for slash then here we want to include from API URLs also we want from D Jango do shortcuts we want to import render now the code for our back end is more or less done we will run now the migrate command and we'll create a super user to test in the future and let's do python manage.py m great and we also want to create super user so again manage.py create super user hit enter um yep let's leave it at that let's say Amir at XYZ do Beck that's not a real email address by the way uh password 1 2 3 1 2 3 yep all right great so let's do python manage.py run server we can do here admin 1 2 3 okay looks fine to me um last thing we need to do uh is to update the security settings let's go to settings so uh the first thing is the csrf uncore cookie underscore same site I want to set this to strict and also session cookie same side so both of them are set to true or strict this actually is going to prevent the cookies and the csrf tokens from being sent from any external requests um but also I want the csrf uncore cookie uncore HTTP only I want to set this to false this is set to false since we'll be accessing the cookie via JavaScript via react by jsx code um but next I want the csrf uncore cookie underscore HTTP only HTTP only that's going to be set to false and also this session cookie uncore HTTP only that's going to be set to true so actually setting the csrf cookie HTTP only and session cookie HTTP only to true this is going to block the client side JavaScript from accessing the csrf and session cookies it's going to block your jsx code from your react front end actually so I have set only csrf cookie HTTP only to false since we will be accessing the cookie via your jsx code from react and by the way for production you will want to set both of those lines to true so let me just add this here for production set these lines to True right and let's comment these lines out and that's it we are done with our backand by the way so we're going to take a little pause and when we return we will use vit to scaffold out our new react project so come up [Music] next all right welcome back to the second part where we're going to create our react project I'm going to use vit to create our react project so if you don't know what is vit vit actually is a build tool and development server that it's primarily designed for building web applications um especially of those using JavaScript Frameworks like vue.js react spelt all of those popular JavaScript Frameworks vit also is known for its fast development and by the way vit means quick or fast in French vit right so uh we're not going to get inside vit today deeply but I'm going to show you how to scaffold out a new react project using vit so for that you want to type mpm create and be careful mpm not MPX so mpm create vit at 4.4 and the name of your project so the name of our project here is going to be front end naturally and make sure that you're inside your Global folder the Jango react off as we have a backand so make sure that you're not inside the backand all right so mpm create V at 4.4 for front end then you will hit enter now if this was the first time you will be prompted to a question um is it okay for you to install vit at 4.4.1 you will simply hit yes and enter and then you will be prompted to this question which is to select a framework and as we will work with reactjs so I'm going to choose react and also you want to choose JavaScript variant let's go ahead now and um change directory to the front end folder I'm going to say mpm install great now we'll do mpm runev all right and this will start our application on Port 5173 so this is our um main page or the the default page for V plus react let's go ahead now and do some modifications for our front end so I'm going to go to the source folder I'm going to delete Del just for Simplicity I'm going to delete both those files app.css and index.css however there is one package that I want to install and let's do mpm install uni versal hyphen cookie at 4.0.4 and we're going to work with our app.jsx now so let's open app jsx and let's do some modifications so uh let me just delete this I will delete this as well and the app. CSS so that's fine instead here I want to import cookies from the universal cookie that's it um also I want to change the functional component to be a class-based component so okay I'm going to delete everything actually so the first thing that we want to do here is to instantiate cookies class by creating that cookies object so new cookies okay also we'll say class app extends uh react. component then we will create a Constructor naturally and uh here props and here super props all right then here we'll say this do state is equal to then we'll have the username the password and the error if any so username initially is going to be set to empty string here the password password and the error and also um is authenticated set to false so that's the initial state of the authentication so we wanton the life cycle method uh the component did Mount if you're not sure what is that I recommend you check out my react course for backend developers in general um I will leave the link to that video in description below but I'm not going to explain in details that um so this. get session here all right so that's simply um in react class components um this life cycle method executed after the component has been rendered to the Dom for the first time so that's a common place to perform actions that need to happen after the initial render like fetching data from an API or you know whatever setting up event leners for example whatever you want so that's what component did Mount in a nutshell next I want to create a method um I'm going to call it get session and here I'm going to use the fetch API to make Network requests so we want to fetch from API session all right and also we want it from the same origin right we want um we want that URL to be on the same origin with the same origin credential settings so we're going to set the credentials credentials yep and we want it as same origin right if you will not try it like that if you will not do the credentials set to same origin we will not have any interaction with the back end with d Jango and as fets Returns the promise so we'll do do then and rest here so we're going to parse the response as Json so um we return here res do Json open close pen do then again and I want the data so here I'm going to console log the response to the console so we'll do console. log and data and in case of the data is authenticated then in this case we will update um the user State the authentication then in this case we will update the user state so this do set State and here uh open close curly brace and we will set the is authenticated to True otherwise so here say else um this do set State and we'll say here is uh is authenticated is set to false and in case of any errors we're going to catch them via DOT catch and here I'm going to pass the error as the input we will log or we will console log to the terminal so console. log the error itself whatever the error is is so let's go ahead now and do who am I as a function that will return uh here we're going to again use the fetch API from API SL who Mii and then we have the headers content type is set to application Json naturally so application and the credentials of course will be set to same origin um then returning the promise then uh we will take Crest again data and we'll see something like you're logged in uh double G you're logged in as and we will display of course the username so data dot username let me just make it clean like that and we are going to catch any potential errors that might occur uh so we'll do like this console.log whatever the error is and don't forget the semicolon and we are done with who am I the next function that I want to create is handle password change so handle password change that's the the function that it's going to take an event so let me explain very quickly this um handle password change method ahead so this method is going to handle changes in the password in whatever the the new password that you're going to set so it's going to take um the event as input as parameter it's going to be typically triggered when you as a user will type in an input field right and then it will update the password state in the component with a new value entered by you okay and that's a common pattern in react by the way for handling controlled input components so let me show you how we can um Carry On so this do set State and here I want to uh set the password to event. Tar target. value to Target whatever the value that you're going to enter in the input field and also I want to repeat the same thing with the username so let's say you want to change your username um so I'm going to call it handle uh handle user name change so again it's going to take event this do state again it's going to change the state of the username to whatever you are entering here the event. target. value all right hope that's clear enough for you guys now I want to create another method I'm going to call it is response okay and I'm going to pass here response or set it as a main parameter so this method basically is going to be designed in a way to handle responses from um the network requests like those made with a fetch AP so it's going to take the response as we have set it here um and we'll check if the HTTP status code Falls within the range of from 200 to 299 we're going to set it between 200 and 299 and the reason for that to make sure that it uh will represents a successful response the way to do that is I'm going to check here if uh response do status more than or equal 200 and response is less than or equal 299 okay in this case I'm going to return the response do Json else I'm going to throw an error okay next let's create um the login function so login is equal to uh oops function that takes an event and and it's going to Let's we will do the event. prevent default to prevent the default uh behavior from submitting when you will uh click so event. prevent um it's always not available I don't know why in in vanilla JavaScript and well everywhere jsx and everywhere prevent default this actually is going to prevent the default behavior of submitting when you will click on that button and we want to make so uh I want to make a post request now to API login we're going again to do fetch again API login and uh method naturally is post and eaders content type is application Json and then the next line is very important that's going to include the csrf token so X csrf token is going to be set to cookies. getet here the Cs or the csrf token all right then the credentials credentials is set or are set to as always same origin and then body here json. stringify username this.state do username password set also this. state. password and this is natural is going to return a promise so then and we're going to check out if U the response is okay so is response okay that we have created and then we want to console log the data the next is very important to do so we want to update the component state to indicate the successful authenication so to do that I'm going to type this do set State and we're going to set is authenticated we want to set it to true and the username is empty string password is empty string error is string uh we want to catch any potential errors so catch error and here we want to console. log this error and then we want to update the component state to display the error message so again we'll do this do set State and here we'll say wrong username or password the last method that it's remaining before we render everything is the logout and let's again do logout equal to Anonymous going to return fetching again from API I think this became a song now right API I just don't forget the slash API um the route is log out we want the credentials also we want to return a promise then this Dot is response okay not if response it should be is response okay wait hold on um if response okay that's is response okay not if response okay I apologize for that guys so I'm going to change it everywhere that's is response okay all right so let's get back here is response okay that's bad better and also we will return uh or we return a promise so here we will have again the data and we're going to console log that data and again we are going to update the state of the authentication so this do set state is authenticated is set to false and again we're going to catch any error and that's it that's the log out method all right so we have written a lot of code I see um okay guys so now we are going to render like that so I want to see if not this do state do is authenticate then I'm going to return div with a class of container margin top uh three then I will need H1 tag say react cookie off um const cookie is equal to Let's a capitalize C here all right so we'll do like that okay still we have something not right so importing index.css okay all of that um is really not needed so let's go to main let's delete all that um the index CSS that's fine export default app all right and I don't know why nothing is appearing so let me just review the code very quickly and I will be back when I will discover what's going [Music] on all right I'm back and I've discovered a few errors so is authenticated make sure that is authenticated is written this way so um the a is capitalized the next thing I don't know why is US state was imported by mistake and I haven't even um notice that import react from react and there we go so after the breaking line I want um h2 tag and here we'll say login and we will have a form uh not action actually I want onsubmit so inside the form submission we want to pass this Dot Login okay and then after I will have a div with uh a class name of form group so form group and inside the div I want a label so label HTML 4 username so that's username and here we'll type username all right and also I want input Fields so input the type is text and also okay I'm going to give it a class name of uh form control so form control and also I'm going to give it ID so the ID here is also username all right and I'm going to do the same thing with um the password so I'm going to take all that actually and duplicate it so HTML for username that's the password of that username so password also the the type here is password not text so password and class name form control that's fine and the ID is password but that's not all so let's just um how to do let's do like that and put the class name under the type and put the ID under the class name and then I will uh shift the closing tag down a little bit now I want name to be equal to password all right next I want uh value so value is going to be equal to this do state. password after the value I want on change so on change not on Camp playay on change yep uh this dot our method handle password change so handle password change that's the one that we want then I'm going to create an ested div here this dot state. error and and then I'm going to create um small tag we'll have a property or we'll have a class name so class name we're going to give it text danger that's uh red color text danger and here I'm going to pass the this. state. error all right and then after here I want a button uh with a class name of BTN the bootstrap classes BTN BTN primary and by the way speaking of bootstrap why nothing has [Music] [Applause] changed and um just go ahead and open your browser JS the liver um the right bootstrap copy that yeah well actually let's take whole thing like this okay save and boom apply to our code perfect wrong username or password perfect that's also working also don't forget that that's of type submit so I don't know why I forgot that type submit right and here let's start login and then here we want to return we'll have container again margin top three and we'll have H1 tag say react cookie off and also a paragraph so let's just change that to P that's a paragraph and we'll say here you are logged in and then after we will have two buttons one for who am I and and another one to log out of the page and we'll have a class name of BTN BTN primary so BTN uh oops BTN primary margin right two pixels okay and uh here I will say who am I and and another button that's going to be red so we'll make it danger so let's do here danger we say here log out all right and we are done with our UI actually all right so uh quite a code we have written here together all right so one important thing to do before we uh start uh building our project is that inside V.C config.js you will need to set the base to static so base here we'll set it to static all right and that's it uh let's go ahead now and build our application for production so um I'm going to kill the server going to type npm run build is going to build uh this folder here with all of the assets there we go the index.html all right uh let's shut all of that now be careful that what we have done now is very important because that will allow our Django backend um to use this file this all of the everything in the disc actually all of the Assets in order to serve up our react application right so let me shut the index.html for now and let's open the settings inside our project so settings.py and inside the templates I want to say basore dur dot join path open close peren front end okay so that's the first thing static file uncore and that's going to be equal to the Bas dur dot joint path open close per and pass here front end and also uh our this inside the front end that was uh built by vit so this here right and that's basically it if you will not be able to run join path if you have installed an older version of Jango um make sure to uh import the operating system module and then instead of Bas d.join path uh you will say os. path. jooin all right so this is instead of join path all right so hopefully this is clear enough for you guys let me just go to URLs one more time and let's actually create a function I'm going to create a function I will call it index underscore View and that's going to take a request as an input and it will return [Music] return render request and here this for/ index.html all right and then after we're going to add that New Path here so path index view this uh function that we have just created name set to index double quotes to single quotes for consistency to look nice all right and we will not forget of course the comma the commas matter in Jango so since D Jango is going to serve up the front end the csrf cookie will be set automatically so uh from the project truth actually we want to go and uh run our [Music] server so what I've done here is I've cut the whole folder the front end folder and paste it inside the D Jango project so let's go ahead now and try out if everything will be as we expect or not all right now I'm inside my folder D Jango cookie off let's make sure that um the uh virtual environment is activated and it is indeed activated now let's do python manage. pyun server we don't get any errors here which is a good sign um but we have here a static file the directory front end dist does not exist so um you cannot find actually the the dist so what I want to do now is I will uh delete the whole this folder I'm going to um run another terminal instance and uh we will go to the D Jango cookie off we'll go to the front end and then again we will do npm run build great that's the proper dist now let's go back here to PPN v shell let's kill the terminal and again you cannot find front end dist so let's check out our static files there okay instead of doing it this way we can do it differently so um we can do front end and we can do this now save that and perfect this was the error so you will do front end and this now our D Jango back end is serving up properly our reactjs via vit and let me just show you uh in the dev tools here if you will go to console uh let's refresh you will find here that is authenticated is false we're not authenticated right and if you will go to the application in the cookies in http1 127 you will find here that we have the csrf uh and uh we don't have the session yet so let's just open let's keep that open now uh oops let's keep that here um yep now if you will click on view site you'll find that you are already logged in right so let's check out here in the console uh refresh and now is authenticated is set to true and let's take a look to the application to here and boom we have our session ID so you have your csrf token of course and now the session ID has has been created right and you can log out and you'll find here successfully logged out all right in the application there is no session ID all right so thank you so much guys for watching the whole tutorial I really appreciate it and if you want to see more of these videos please let me know in the comment section below if you have any questions anything that it's not clear for you also please let me in the comment section below and yeah I will see you in the next video till then stay safe and be well take it easy [Music] guys
Info
Channel: Bek Brace
Views: 2,853
Rating: undefined out of 5
Keywords:
Id: GnU7y-9D71Y
Channel Id: undefined
Length: 54min 53sec (3293 seconds)
Published: Sun Oct 29 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.