Django API Authentication using JWT Tokens

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this tutorial we'll create an authentication system using jungle before we start building the app i would like to remind you that this video is meant to be combined with other videos so if you want to use jungle with angular react next js view nxjs or svelt i provided some links in the description below also make sure to check scalablescripts.com now let's start creating the project we will use django rest framework first make sure to have mysql community server installed and if you want to see the data you can install mysql workbench now in django restframework.org click tutorial quick start and these are the commands to install django already did it so i can run here jungle admin start project i'll call it alph and the project is created i'll go to the folder and inside i will create another app so django admin start up users now everything is created we can run this project so python 3 manage that pi run server is a command and this will run the server on port 8000 so copy this url paste it here and this is our createdjango project now let's open the project with my ide i'm using pycharm professional here but there is a community version which is free also visual studio code is also acceptable so here we have two folders this is the main folder for configurations and this is a folder that we will create the users and we can log in first let's go to the settings we will add some packages here the first one is the rest framework and our user sub that we just created this folder so we are done here also i will stop the server here and i will run it inside my ide here so python manage that by run server so this is just my personal preference nothing will change now now let's go to the users and let's create our user model creating a user model in django is different than creating other models creating other models is really simple but for the user model we have to first import from django contrib of models we'll import the abstract user because django already has a user inside and we have to extend our current user with this abstract user and now our model will be class user we'll extend this abstract user let's add the fields that we need we need the name which is models char field so these are the database field that we will create later so max length of this field i will put it 255. we need an email so it's the same i will copy it the difference for the email is that is also unique and a password so i will copy this also django also creates a username field it is required for the abstract user but we can override it by saying that the user name is none and the username field will be our email not like this but like this why did this change because uh django usually logs in with a username and a password but we want to log in with an email and a password and these are necessary to do this um change also we need to add required fields here to an empty array so now this is our user model still we have to add it to our settings and in the end here we will add auth user model we have to specify our user model which is users which is a folder and in the models is the user model so that's it so we overrided the default user for django now let's add the migration for this user first let's connect with the database so in the settings we have a database here and my database is mysql the name here is the database that i have is youtube django out the user is root password is root root in my case and everything else should be correct so i don't know if i have to specify the host so i'll connect also with mysql here output data source in a pycharm community you won't have this tab so you should use mysql workbench the user is root password is root root and the database is youtube django house so this is my empty database also make sure to install the mysql client so for for django to use mysql we have to install mysql client i already did it so python3 so this is already here now this is complaining not sure why it is because we have to make the migration so to run the migrations we connected with the database now we have to run a command python 3 manage that pi make migrations and we created migrations here in initial we'll see now we have a bunch of fields here but this is because we extend the user and the fields that we added are these three fields here now let's migrate so to migrate we have to use migrate here and the migration are created if i open here we can see a bunch of tables here the table that we want is this user's user where we have a bunch of fields but we don't we won't use them we will just use the name email and the password now let's uh add the the end points that we want so in the urls here from jungle urls we'll import path and we'll import include and we'll add the url pattern for the path api slash and inside so the second parameter is include we will create a folder here not a folder file urls.python and this will include the users with the urls folder so this will accept all the endpoints of the user and let's add here the urls so i'll copy again this paste it here and we need to add the register route here so the path for the register route is just register and for the function we will create it in the views now so here let's create the register view first let's import from django from sorry rest framework views api view and we will create the class register that extends this api view so the api view has a get and a post function and this will be a post function post and the second parameter is the request and let's pass for the moment and this function this class will be used here so from the actual folder models not view sorry import register view i will call it register view better and this register path will call the register view as view so we added the url now let's complete this function to create a user we have to create first the serializer for the user so we'll create a folder here serializers so in the serializer file now first let's import from rest framework import serializers and create the user serializer class user serializer this will import from serializers model serializer inside here we will add a class meta where we will define the model so our model is the user model so from models we need to import the user and the model is the user model that we have second we need the fields as we saw the user has a bunch of fields we don't want to use them so i will specify the fields that we want to use in this case so we want the id we want the first so no not the first name so we want the name email and password these are all the fields that we want to use now we created the serializer let's use it here so first when we create the user we will create the serializer so serializer is equal to user serializer let's import it from serializer import user serializer and we need to pass some data here and the data will be getting it from the request so the data is equal to data we can also validate the serializer by using is valid and if it's not valid we want to raise an exception to true so if we put some data that we will fail we want to erase this exception in the end we will save the serializer and we want to return it so to return it we have to import from rest framework response we want to import the response and in the end we'll return response of serializer and the user that we want is dot data so this is our register view now let's use it so to test it we have to install postman so if you don't have it me make sure to download it and now let's open it so the endpoint is localhost port 8000 slash api register and we want to send a post request in the body we will send the name a email ata.com and the password a so this is the data that we want to send so with this we want to register our user let's send the request so we got an error oh actually i forgot here to run the server so let's send the request again and we created our user but we have a problem the password is returned as it is if we see the users in the database we can see that some values are added but we don't want them but the password is set as it is we want to hash it so how do we hash the password we have to do this in the user serializer so django already has a hash password for us so here we can override the default create function and these are the validated data which if all are provided so this will pass what do we want to do now is to extract the password we can extract the password by using validated data pop the field with password and we can pass known here so we extracted the password now let's create the user so instance is equal to self model meta sorry model and will pass validated data so this two stars are the validated data without the extracted password so we will create this user now we'll make the condition if the password is not none then we have to set the password so instance set password to password this function set password is a function that is provided by jungle so we already have access to this password and in this case the password will be hashed let's save it and in the end we need to return the instance so this is a function that sits in between of the view and the model creation so with this now before i create the user i don't want also to return the password usually when we register something we don't return the password uh and how to hide that password there so we have to add here extra pw args so here we can add the options for each property here and the password the option for the password is write only to true this means that the password is only for write only purposes and if we return the user we won't show the password so let's create another user now b and bsb.com send and we successfully created the user so as we can see the password is not returned here but let's see in the database what is the value of the password as we can see here the password is hashed so now with this user let's use this user to log in so let's create the login function so let's go to the views and here we'll create login view and this will extend the api view as well and let's add here a post request and this will have a request as well so let pass here so i can add it to the urls so here we'll add the login view as well and the path will be login and this is the login view so now let's complete this function so we will send in the request an email and the password so first let's get the values email equal to request the data email the password is the same now with the email we want to find the user so let's find the user which is equal to user we need to import it from the models from models import the user user objects find so filter sorry with the email is equal to this email that we have and we want to find the first user because the email is unique so we found the user make the condition if user is none we want to raise an exception raise exceptions so let's import here exceptions so authentication failed so will race authentication failed user not found so if we go to this line it means that the user is found now we have to compare the password so we cannot compare it directly because the password is hashed but we have to use it like this if and not so i will do the opposite user check password so we can put we can use this function which is already provided by django so if it is not provided we will raise another exception incorrect password and if we go here then it means that the user is the right one and the password is correct so for the moment just return response the user and then we will add the extra things so let's post to login this is a post request at the body we will send an email which is b b.com and a password which is b send and we get an error so we get this error because the user is not json serializable i will return just message success here because when we login we don't want to return the user we want to return the token so it means that this is successful if if i provide the right a wrong email user not found if i provide the wrong password incorrect password so now is we are ready to use jwt tokens to create tokens we have to install another package so i will use it here python three pip install by jwt so this is a package that we want to install now and we want to use it first let's import it so we need to import gwd we need also to import date time so here now to create a jwt we need a payload and this payload will have these values first the id which is the id of our user so we'll store the user id here second parameter is the expiration and here we want to set how how long with this token will last so date time date time utc now we will add time delta minutes 60. so we'll keep this token for 60 minutes 1 hour and i 80 is the date which this token is created so it is utc now so these are the data that we want to use now and let's create the jwt jwt is equal to not jwt but token is equal to jwt and code we need the payload the second parameter is a secret so you can put the secret in your application wherever but i will put it here directly and the last one is the algorithm which i will put h s 256 and that's it and the token i will decode it to utf-8 so this is our token let's return it here so jwt will be equal to this token and let's see what it looks like send request and this is our jwt token this will be used in order to login our user still we don't want to return it like this so we have to set it via cookies so let's set it let's return this token via cookies first we need the response so i'll cut the response here we'll create a variable and we want to return the response here and i will do it like this response that data is equal to this now let's set this token to the cookies and we have to do it like this response set cookie the key will be jwt this is the name of the cookie and the value will be this token that we have we need another parameter which is http only to true because we don't want the front end to access that token so the only purpose of that token is to be sent to the backend and let's see what this looks like we have no cookies right now if we send a request we have a cookie now so this is the value of the cookie and it is http only now we have to use this cookie to retrieve the user but first there is also one last change we need to install also another package and this is course headers sorry it's jungle course headers jungle course headers so once you install this package we have to use it here first why do we need this package the first reason is the course problem i don't know if you have encounter it but if the front end has a different port than django the request won't happen and it will it will throw an error so we have to add this course headers here to the installed apps in order to prevent that error from happening we need also to add the middleware so here we need to add the course header middleware so this is necessary to prevent the error also we need two variables which i will add them here these are these two so course origin allow all is this to prevent so this is to allow all the front-end ports to access our app because otherwise it will prevent uh from using them of course allow credentials this is really important because we log in with cookies and we return the cookie if we don't set this to true then our front end won't be able to get the cookies so we have to set allow credentials in order for the front end to get those cookies this won't change anything in the request here but this is used only for the front end now let's get this token in order to get the authenticated user so let's create here class user view is a api view here and this will be a get request let's pass and let's use it to the urls so this will be user and this will be the user view is here user view now let's go to the user view and now we have to get the cookie and from the cookie to retrieve the user so first let's get the token which is equal to request cookies get jwt so like this so with this we get the cookie that we want let's return a response with the token so we can see that we got the value so let's send a get request to a user when we switch tabs it will preserve also the cookies here so don't worry as we can see we got the cookie because it is preserved now we got the cookie let's uh decode it to get the the user so first if the token is so if not token sorry if the token is not set we need to erase an exception unauthenticated because we are not logged in like that then we will make a try accept so inside we'll get the payload which is equal to jwt decode this token is the first parameter the second parameter is this secret here so is the same value and the last parameter is the algorithm and that's it basically so this time the algorithm will be an array with this we get the payload and if it fails we'll still erase the exception so the exception here is jwt expired signature error so we got the payload the payload is this here so inside we have the id for the user so let's get the user user is equal to user objects get and we have to pass the payload id here and we get the user so let's return the user in the end and we are done so the user is not json serializable so we have to use it with serializer is equal to serializer user serializer sorry with the user inside and we will return the serializer that data here let's see so we made a mistake here but it means that we successfully got to the user so i will switch this get to a filter where the id is equal to payload id and i will get the first value so with this change we successfully get the authenticated user and we don't send anything just this cookie so this is how we get the authenticated user now let's add the last class which is a logout logout view api view here this will have a post request and [Music] what do we want to do now is just removing the cookie so response is equal to response response delete cookie jwt and the response data sorry is equal to message success and we will return this response so is this easy let's add it to the urls logout view and this is logout logout i'll copy this url now paste it here and now we will post to logout so we were authenticated here so we can get the user let's pause the logout message success and we don't have any cookies send the requests we are unauthenticated so we successfully logged out if we log in again and we get the user again we get the user so this is how the authentication works in django i hope you like this tutorial if you like it please like share and subscribe thank you
Info
Channel: Scalable Scripts
Views: 30,645
Rating: undefined out of 5
Keywords: django, django rest framework, jwt, jwt authentication, python jwt, python authentication, python jwt authentication
Id: PUzgZrS_piQ
Channel Id: undefined
Length: 37min 5sec (2225 seconds)
Published: Mon Feb 08 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.