FastAPI (Python Framework) - Authentication APIs (Register, GET Token, Refresh Token, User Details)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys welcome to describly and today I will  be teaching you user authenticated system in the   first API okay so there I will be using uh JWT  that is Json web token to create the user token   okay so in this tutorial uh basically I  will create a four API endpoints one is   slash users that can be used to register a  new user account token that can be used to   generate a new JWT token slash auth slash refresh  token that can be used to refresh the JW token   and slash user slash me that can be used to fetch  the authenticated user details okay and apart from   that there are a couple of things that you will  learn in this tutorial one of them could be like   how you can connect the first API with the mySQL  database okay and also you will learn how you can   add the middleware in the fast API so in the last  API endpoint I will teach you uh how you can add   the authenticated user in your request object  sorry about that so that whenever you need to   know the authenticated user you can fetch it from  the request apart from that I will also teach you   how you can configure the connection pooling  in the SQL Alchemy okay so let's get started okay so I have created an empty folder and this  folder as you can see here if I type PWD this is   on my desktop okay and there is nothing in it  right now okay so I'm just going to configure   the application inside this folder so for that  I'm just going to create a file requirements   dot txt okay so here let me copy paste all  the requirements so we'll need fast API uvi   con python.unb to read the environment  variable identity setting to configure   the application settings password this  will be used to encrypt the password token and Pi MySQL will be used to connect  the mySQL database and SQL Alchemy this is   the eloquent that we will be using in this  fast API application okay so let me save it   and let's create the virtual environment now  so for that Python 3 hyphen M the EnV and venv   okay so our virtual environment is created here   so now let's say install the dependencies  so before that let's activate it p e and V   win activate Okay so it's activated now so let's  install it if install hyphen r requirements.txt okay so uh application is now ready let's  create our first route so for that let's   create the main dot py okay so here let's import  the first API from fast API import first API   class okay so let's get the application  instance app equals to fast API instance   okay so now let's create our first route  that is app Dot get and we are going to say   slice only and then we will create a method  def let's say uh let's call it health check okay this will not receive any argument it will  just return a Json response so for that let's   import the Json response class from the first API  so first API dot response is import Json response so Json responds and here we need to provide  the content this content could be anything but   I am going to provide the dictionary okay  so I will say uh status equals to running so now this is done okay so let me close this  terminal python terminals and let's install the   oh sorry start the first API application so for  that we can say uvi con hyphen m not hyphen m   main colon app if an open reload okay so this has  now started our first API application we can copy   okay and let's open the browser let me create  the other browsers and let's see okay so this is   running now so we can see the status running that  means our first API application is working okay uh   as you might already know that fast API comes with  pre-built documentation okay so we can open the   documentation of the API using slash talks okay  so this will open the circuit documentation of   the first API so as you can see currently we have  only one URL that is Slash and it's a get method   and when we execute this one we'll get that status  running okay that means our application is running   perfect so uh what next let's start  configuring our application okay so for that uh   let's create a folder called core so I I prefer to  keep all the configuration related things inside   the core folder because this is the uh that is the  core of our application right so uh let's create   a file here let's call it config Dot py okay and  in this config.py I'm just going to put MySQL and   JWT related configurations okay so before that we  need to create the dot EnV file also so that we   can put the environment variable there okay so dot  ENB and here I am going to copy the MySQL related   configuration that I have okay so let's paste  it here so I have added the MySQL user password   MySQL server and port in the database name okay so  let's now add the configuration in the config file so for that uh let me copy paste here okay OS is missing so  we can say OS here so this is the basically   settings for this application that I am going to  use I have not added anything extra except what   we need in this uh video tutorial so to access the  setting let me create a method called get settings and this will just return the instance of the settings   this is your method and we can say this will  return the settings perfect so now we have   our my SQL related settings we can continue  working on the user registration API right   so for that what I'm going to do I am just going  to create another folder here I will call it users   okay and inside the users what I'm going to do  I am going to create a couple of files one of   them would be let's call it routes dot py so  here I will be defining uh all the end points   that relates to the user okay so I'm just going  to add the uh router here API router so prefix   will be users and types will be the user again  or you can say users whatever you like to call   and this API the route will come from the fast API  okay so we can say from fast API import API router   okay so using this now uh what I'm going to do  I'm just going to create the slash user's route   okay so since we have added the prefix here uh  so when we create the route we don't need to add   anything there so if we just leave it empty  that means we are calling this slash users   route okay this is status uh actually  this will also come from fast API okay   and this is now done let's  create the method So async Def   create user okay so here I'm going to uh I  am going to receive the data from the request   and for that I will be creating  a class called create user   request okay and I will get the DB instance as  well this DB will be coming from SQL alchemy.orm   import session okay and this will be a  dependency okay so this will be depends   and this bill depends upon we will create a  method uh next get DB and this depends will   also come from the first API okay so let's  first create this DB1 okay so let's create a   database configuration in our core folder  right so here let's create a database Dot py   so in this database dot py what I'm going to do  I'm just going to copy and paste the configuration   again okay so this is the configuration so  here I have uh imported the settings that we   created in the config.poe file and I'm  creating an engine SQL welcome engine so   here I have added the database URL as you can  see this URL is coming from here that we are   reading from the environment variable  right and then I'm creating a session   class and this get DB this will be a generator  actually so this uh this what this generator does   whenever you call right it uh creates a session  and whenever you call the query it executes the   query in the session and once the request is  done this will close this particular session   okay so apart from this I have added  this Auto commit false that means our uh   this whatever we do will not be committed  automatically and out of list is false also here   and in this engine uh I have a full pre-pink proof  that means like whenever a connection is about to   be used that will make a dummy connection  or you can say select one to the database   just to check if the particular Connection in  the pool is still alive and if it's not alive   just then then that connection will be recycled  okay and this pull recycle what it does it uh   destroys the connection after 300 seconds  and recreates the connection in the pool   that means like your connection in the pool will  be refreshed in every five minutes you can change   this value as per your configuration right this  pool size is basically how many connection we are   going to keep in the connection pool and this Max  overflow right is like let's say in in a request   we are making more than five connections right  so in that case your connection will overflow   from what you have defined in the pull right  so max overflow zero means like once the uh   purpose of the connection is done your overflowed  connection will be destroyed and your pool will   have high connection only okay so I hope this  makes sense so this is done now our DB is done   now so let's continue working on this one so we  need to import this get DB so we can say from   code.database import get DB okay  so we have the getdb here now   I will just say pass for now let's create this  create user request class okay so for that   uh sorry about this I will  create a file called schema schemas.py so here you can create all the  request classes that you will need your   in your uh application right so here I have added  the create user request class and I have extended   the base model that is coming from the pedantic  so our request will use uh for uh input one is   first name last name email and password okay  so let's import this class in our the route   file so we can say from users that is our users  folder dot schemas import create user request   so this is uh don't know and for the for further  mySQL database so I have already created a table   you can see the structure here I created I  did the first name last name email password   is active is verified verified at registered you  don't need this in this tutorial but I have added   this uh just to show you how you can evaluate  the user okay so we'll see that in the upcoming   uh when we when we build the user login and  all okay so let's continue working on this code   so to create the user account I I don't prefer  to keep that in the same file because if you   have lots of route your file will get like  uh messy so for that I I generally create a   separate file for this kind of applications so  let's create a services dot py file okay so I'm   just going to write the logic of creating  the user in this one okay so for this uh to create the user before we can write the logic  we need to create our user model as well right   so for that let's create a another file called  models dot py so here I'm just going to create the   user model so for that I have copied and pasted  again here so I've created a class user model   and I am specifying the table that is users as you  can see here this is the users table and this has   all these fields only that I have added here so  you can see first name last name email password   is active is verified verified it registered it  this kind of fields okay so this should extend the   base and this base uh must come from your database  configuration so you can see I have imported from   there itself so now we have our model class  as well so let's uh continue working on the   service class okay so in the service uh I  will again copy and paste so uh for this uh create user account so I've added a  method called create user account here   what we need to do we first need to check if  the user email is already registered right so   we will fetch the user from the DB if it's  exist then we will throw an exception that   user is already registered with us okay and  if it's not then we will map the request data   with our model fields and we'll say DB dot add  this will add the new user and after committing   this will be persisted in the database then  we will refresh the user and we'll return the   same user but there is one thing missing that  is our security right we have not created a   method through which we can hence the password so  let's create a in this core folder called security dot UI so in this security  what we need we need a method let me rename it security and we did a method  called get password hash okay so get password has will be a simple method we can we can  put that there also but I just I want   to put these kind of things in a separate file  Okay so it could be like the password context   dot hash so how can we get the password  context or password contacts will be uh   coming from the pass leave Library okay so let me  copy and paste that there so password dot context   uh crypto context and then we can create the  password context using cryptic context so Crypt   context is like this so here I have added  the schema decrypt and replicated Auto sort   so this will create the password context and using  this password context we can has our password   okay so now we have successfully created our  create user account method so let's import this in   our route so we can say from users dot services  import create user account so we can say uh a weight create user account this will need the  data data equals to we can say data and this will   require DB DB equals to DB we can put okay once  the user account is created what we need to do   we need to return a response right so we can just  return a Json response we can say return or we can   just return the user details also but I just want  to return the Json response so I will say Json   okay let me import the response  class Edge build from Fast API dot responses import Json response suggestion  response so sorry not HTML Json response this Json   response will receive a Content let's say called  payload message payload so this message payload we   can create a dictionary we can say message and  this message will be the user account has been successfully created okay so now we  have successfully created a route   that can create the user account in ODB  right so let's say refresh the page here   okay it's not here okay so our this particular  route class is not yet registered with our   application so for that we need to import  that so we can import from users dot routes import uh router we can say as user router  and in with application we can say uh app Dot   we can we can say app dot include router and then  we can pass the router name that is user router okay so we have successfully registered our  user router now let's refresh this page and   see if we have got the uh users so you can see  the user here so this particular username is   coming from this tag so if we go to the uh this  router class so this is basically if coming from   here if I say users and if I refresh you will see  users here and this users slice users is coming   from here if I put let's say here slash  something uh whatever let's say hello   and if I refresh then you will see user  slash hello but since we don't want that   we just want the the users only so I  will just leave it empty okay and this   create user is coming from this method whatever  you name the method that you will see there okay   so we have successfully created our create user  method okay so now let's uh try to create a user   account and see if it's working so we can click  on the try out and here I'm just going to put my   name that is case study Nandan and I will put a  dummy URL called admin at the rate test dot com   and password I will add let's say admin at one  two three execute so this should create the user   account if everything is right so you should see  the message user account has been successfully   created right that means our create user API is  working perfectly fine and if I go to the database   and if I refresh the database then we should see  the uh details there okay perfect so we can see   the first name last name email password that is  encrypted ejective is false is verified is false   verified that it is nothing and but we can see  the created add-in updated all those details right   so that means our create user API is working  perfectly fine okay so let's Now work on our   slash login API okay before that let's have a look  on the first API official documentation right so   under the test user guide and inside that if you  go to the security you will see uh it has very   good documentation that you can use but it's  little confusing sometimes if you are not very   familiar and if you are new so what I have done  based on this documentation I have just added some   simplified the way you can work with Okay so I  have added this methods password context as you   have seen previously and worth the scheme and  all these things how you can configure in your   application right so now let's continue working on  that okay so as you can see in this documentation   we need to create the OS to a scheme and here is  the token URL so these things we need to configure   okay so let's start configuring them and let's  keep going so let me close these files so before   we can start working on the login I am just going  to put some code in this security dot py file so   since we have added a method uh get password has  right so this will create the encrypted password   has right but we also need a way to verify  the password so when the user comes to the   login page and inputs their password we need  a way to verify the password for that I am   just going to add another method and this will  be called verify password so this will again   use the password context dot verify and it will  accept two parameters one is the plain password   and then the highest password so this hash  password will be coming from the database and   plain password will be coming from the request  okay and let's create the oauth 2 scheme okay   so 2 over to create the word to screen video  to import some class from the first Epi one   is uh go Earth to password Bearer so this will  come from Fast API dot security import o path to O2 password better okay so this class we will  be using and let's create the scheme so oh auth foreign we will say token URL so this token URL will be uh  your token URL so in our case this is going to be   auth slash token okay and this is done now so we  can continue working on our path model so I said   auth that means we need to create a folder  called auth okay and for that let's let me   create a folder called auth and in this folder  I will again create a file called route Dot py okay and not a router this will be route so in this route.py uh again I will  create a router okay so I will say   slash auth and this will be called auth  and this we can import from first API   import API router now we need to Define our  token route right so token route we can Define   like this route dot post slash token and this  status we can again import from here and we   will return this 200 status code once uh login  successful right so let's define a method called   async div and let's say it authenticate user  and this will receive some request data and this   request data will be coming again from the first  API so this will be from fast API dot security import sorry or two password request form okay so this will be this class  and apart from this we need to say that this   is the dependency so we can say depends and  Depends also can be imported from first API   and apart from this we need the DB connection  right so we can say DB colon session and we can   say depends get DB so we need to import the  session from SQL Alchemy so we can say from   SQL alchemy.orm import session and this  get DB will come from our core Dot database   import get DB so we have successfully created now  our method definition now what we need to return   it from here we need to return the token right so  we can say await get token and in this get token   we need to pass the data and we need to pass the  DB these two parameters that we are receiving from   the request okay so this get token method is  noted there so we need to create a file called   Services Dot py and in this one we need to  Define async Dev get token this will receive two   parameter that we have passed from there for now  let's say pass okay let's import this method from node this one orthod dots services import token   Okay so not colon this will be equals to so  we have successfully configured our route   okay now let's go to the get token method and  implement this so once we get the request right   to login first we need to check the user  okay so to check the user we need to   check if the user exists or not if user doesn't  exist we can't log in the user so we can say DB   Dot query and in the query we will pass the  user model that we have created in the user   module so we can say from users dot model  import user model and we can say dot filter user model dot email equals to we will  becoming the we will be getting the user email   inside the data okay so let's see what  are the uh parameter of this class   so here we will be getting if I go to  this document right so this is the data   and if you see we will be getting the  username and password okay so we need   to pass the username and password so we can use  the username here so data Dot username and then first okay and here we can say if not user that  means there is no user in you know DB with that   email we can say email is not registered with us okay and let me   import the exception so we can save  from Fast API dot exceptions import HTTP exceptions so we can say user is not  registered with us that means we cannot log   in the user okay but if we have got the user then  what we need to do we need to verify the user okay so we can say if verify password so this verify  password we just now created in our security right   here this will written a Boolean value either  true or false based on the uh what user has   applied so if the password matches it will return  true otherwise it will return false so we can say   we can import this one from core dot security  import verify password so in the verify password   we need to provide the plane password  that will be coming from data.password   as a request input and the user password user  dot password the password has so if this is valid   or you can we can say if this is not valid  we can say invalid login credential okay we can say invalid login credentials if the cursor passes this validation  again then as I said in in the DB I   have added the each active is verified right  so you can add these checks as well so let's   say for that let me create a separate  method here let's call it Dev underscore   very Phi user axis this should receive  a parameter called user model and here we can check if the user is active or not we can  check if the user is verified or not so I'm just   going to copy and paste the code here okay so  we can say something like this if the user is   not active that means we can say user account  is inactive please contact support and if the   user account is not verified then we can say  your account is unverified here let's say you   have implemented a user account verification email  right so if the user account is not verified and   user is trying to login so you can here write  a method trigger user account verification email okay and you can say your  account is unverified we have   resend the user we have resent  the account verification email it's up to you how you want to implement some  of the people uh Implement in a way like your   email has to be verified first but some of the  user Implement in a way like you login to the   platform you can log into the platform but there  is just some limitation and there is a banner   showing up like your account is unverified  something like that so it's up to you how   you want to configure I'm just giving you some  idea how you can achieve these kind of things   okay so now we can call it this method here  verify user access and we can pass the user   custom user okay so if anything goes wrong  this will throw an exception or your code   education list of it here so you don't  need to put any if or anything else here   so if everything goes uh fine then we need to  return the token right so we can say return   and we right now I'm just going to put  a just I'm pasting there and we can say   written access token and refresh token okay so now  we need to write the logic how we can generate the   JWT token correct so for that uh before that let  me create a separate method here private method   we can say get user token why I am doing  this because this method I will be using   uh when we create the refresh token API so I will  be using the same method in that case also so this   will receive the user model and we can also if  the if we are working in the refresh token API   then we have the refresh token so  we can say refresh token none here   so if we have the refresh token we  don't need to generate that we can   return the same one and if we don't have then  we need to generate this okay so for this uh before creating let's let's decide  what we are going to put in the   JWT payload right so we can create a method  payload and in this payload for now I'm just   going to put the ID that will be that will be the  user dot ID so this will the payload is dictionary   but you if you like to put anything else let's  say you want to put the user email I I wouldn't   recommend that but some other information if you  would like to put the in JWT token you can put   this uh put that in this dictionary and this will  be persisted in the JWT token when it's created   okay so this is done now apart from this  uh let's go to our configuration config   file and see what we have added there  we have not added anything right so   to create the JWT token we need a couple of things  like one is the JWT Secret one is the encrypting   algorithm that we are going to use and one is how  long our token is going to be alive right the TTL   of the JWT so for that I am just going to copy  and paste couple of environment variable here   in this config file Okay so this is going to be  let me put it here so this will be JWT secret so   I've added some dummy secret if you don't provide  from the environment variable this will be used   algorithm if you provide any algorithm then  it's fine otherwise this HS 256 will be used   and JWT token expired in units you can edit  in your EnV otherwise it will be 60 minutes   okay so your tokens would expire in 60 minutes so  these These are the variable that I will be using   and what else so let me close this file route over  to okay this is not correct so let's go to the   services let's continue working on this get user  token method okay so here we have uh now we have   added our expiry right so we need to uh go import  that so we can say settings equals to get settings and this createx settings will be imported  from code dot config import get settings   Now using this we can get our expiration time so  for that we can create the access token expiry and this will be time Delta time Delta  let's import this so from date time import   time Delta okay so we can say time Delta that  means this this will use the current time and then   the time that we specify so let's  say Mi minutes minutes equals to   uh the token expiry that we have added in the  environment variable so this will be settings Dot   access token expire in minutes okay so now we  have our expiry also we need a way to create   the access token and the refresh token right so  let's say access token is this and refresh token is this okay and we once we have  both we can return the response so for that let's check let's create the access  token method and the secret token method so   create access token and create secret token I'm  just going to put that in in our security folder   security file so here I will Define a  method async Def create access token okay so this will receive the payload you can say and expiry okay so this expert is going to be time Delta I'm  adding this so that uh by mistake from date time   import time Delta so this will be instance of  time Delta okay so now we have our payload we   have our expiry time so we can say like let's call  it data and then we can say payload equals to data dot copy so we are creating a copy  of the data that we have provided   and we will be adding a couple  of more things here so expired in   for the expiring going to be uh date time that we  need to import first date time means current time date time whatever is the current time so we  can see UTC now and plus we need to add this   time Delta that we are getting from there okay so  we now have our expiry time right so we can update   this in our payload so we can say payload Dot  update and in the update we'll uh we can say like   exp and we can say expiring expire in so this will  be our rate token expiry time and we can say uh token equals to now we can say JWT and this JWT  is not imported so we can import this JWT from this Jose import JW d okay so we can say JWT Dot encode JWT dot encode then we can say payload  whatever payload we want to encode and then we   can say settings dot j w t as you can see this  is this will be the secret so we can say jw2   yes E C or E T I I'm not sure if this is the  variable so let me make sure we can say from   uh core dot config import get settings and  we can say settings equal to get settings   and then okay so this was the variable and then  we need the algorithm that we are going to use   okay so algorithm we can say algorithm this  will be a list so we can say settings Dot JWT algorithm so we have configured our secret  our algorithm and this payload will be encoded   using the secret and this algorithm right  so that means uh if your token is secure   okay and we can return this token so instead of  saving this we can directly return this token   so we have added a method called create  access token so this is now done let's   add another method called uh create refresh  token this will again receive the data and   this will be a very simple method this will  be also a JWT token but we need we don't need   to add the expiry and all in the refresh token  so we can directly say data JWT secret and JWT   algorithm if you would like you can add another  secret a different secret for uh refresh token   or different algorithm for the refresh token  but I I'm just going to uh keep it simple here   so we have successfully added the create  access token and create refresh token   so we can import this in our service uh so  from here we can say from core Dot security   import access token create refresh token okay  so we can say create access token this will   receive the data that is our payload the second  parameter it will receive the expiry so this is   this year further refresh token if not the  refresh token that means if the refresh   token is not provided then only we need  to create the refresh token right so we   can say refresh token is equal to create a  refresh token and this will just receive the payload that that is our payload so if  you want to put any uh other things in   your refresh token you can put it but for  the Simplicity I'm not going to change this   okay so we have our access token we have our  refresh token right so let's uh written this   so in the first API we can also create a  response class okay so I'm just going to uh   sorry here I'm just going to create  a file called uh not folder sorry   responses Dot py so in this one I'm just going  to create a structure for the token so that   will write this so from Identity import base  model and this token response will have have   access token refresh token token type that  is going to be the bearer and the expiry   time okay so let's say return  this one here return token response and we can import it from orthod responses import   token response so this token response will  have access token equals to access token refresh token equals to refresh token expires in equals to uh access token expiry   in seconds I'm just going to return that in  seconds okay so here I can put a comment in   seconds so this time Delta will  be converted into in seconds okay   and fourth parameter type token type Bearer I'm  not going to provide as the default value is the   bearer so it's fine so we have successfully added  our get user token method and this will be the   refresh token sorry so this is now done here we  can now return this method okay get refresh token   and we can pass the user equals to user will  be don't have the refresh token so it's fine   uh create a user access token we have added  the async so we need to add the weight here you can add the weight but to add  the event we also need to make this   make this async so this is done now  and here and calling we can say a bit so now uh users token API is also done let's  check it let's check this so token is done   here we are getting the token perfect  and let's see if we have registered this   so in the main we have not yet restart  right so we need to import that from   Earth dot routes import router you can say token  router or Earth router whatever you would like and we can register this so now this is registered if we go to our Swagger  and we refresh the page now we should see the   auth slash token okay so we  have our slices let's open here   and we can also see the create user uh  request will take these four parameters authenticate user will take username and password if validation error happens then what will be the  response type HTTP HTTP validation error happens   then what will be the response these kind of  things we can see it here it was not in the   previously when we started this video tutorial but  it's there now so we have a created the user here   and let's try to login now okay so to login we can  click on the try and here we can add the email so   let me remember the email so this is admin at  test.com so this is the email and password was   admin at one two three okay so  let me try and see if it's working   internal server so something went wrong let's see  object has no attribute query okay so let's see   what went wrong data equal okay here we should  pass the DB instead of data so this was the typo   let's try it again see if I click execute your  account is inactive so now you can see like uh   since it's uh is activated zero that's why  you are getting this message if I make it one   so your account is activated now if I try it again  this will say your account is unverified please   we have resend the account verification email so  that means uh if you would like to configure your   email verification thing there you can configure  it but for now I'm just going to make it one   so now user is active and verified as well so  if I click on execute again some error occurs   and has several type list alert them is not a  list this will be a string so that's why this   already is coming so let me just remove  this and save this file okay and let's go   to this space again let's try so email  is our admin at test.com password is   admin at one two three okay so it's cute so as  you can see now we have got our access token   I'll place the refresh token  so if I open the access token   let's see uh what is there in the  token so we can go to JWT dot IO okay so here we can paste our token so we  can you can see currently the payload has ID   that is 1 and the expiry that we have added so  we have added one RX query so it's four seven   that is going to expire and you can see like  currently in my local time unit it's a three   seven so uh just after one hour okay so that  means our token API is perfectly uh working now so now let's continue working on our refresh  token API okay so for the refresh token API   we need to add the refresh token here  in this route file okay so for that uh we can say a slice refresh okay and again  we are going to return the 200 codes we   can say again a method name async Dev  and this will be refresh access token   refresh access token and this is refresh  token actually going to receive the uh   refresh token that is that was sent during the  login right so we can say refresh token and this   will be a Str and this will come in the header so  we need to import the header so if you want to get   I mean get this token as a body parameter you can  get it but I would prefer this in the header so   we can say header and what else we need we need  the DB so again we can say DB session and Depends   get DB okay so similar to uh get token we are  going to create a method called get refresh token get refresh token this will accept the  token that is the refresh token and DB okay so let's go inside the  service and create a method here let me call it facing Def I get refresh  token so this will have two parameter token   and uh another one is DB okay so we have we have got the token right  but we need the pill token payload okay   so since we have added the user ID in the token  so we don't know like when we create the token   we need the user detail right so to get the user  detail we need to decrypt the refresh token and   get the user ID from there so for that we need  the payload so to get the payload uh what we can   do let's add another method in the security and  this method is going to be get token preload okay   so this get token payload is something like this  get token we can import this JWT error from JWT so this is now uh this will return us the token  payload so let's import this method in our service   so we can say get token preload and here we  can say get token payload we can pass the token okay now we have our token payload we need to  extract the user ID from there we can say user   ID equals to payload Dot get and we can say  ID and this none we can say if not user ID   that means if the token doesn't have the user  ID then that means like this is not available [Music] okay again if there is no user exist  with this ID that we have got in the   token that means this token is invalid  so we can say invalid refresh token again   and if we have got the uh user detail  that means we can now create the   user access token so we can just return a weight  and this method uh get the user token okay so we   can just return this method the way to get  user token you can pass the user equal to   user and here we have the access token so we don't  want to generate a new access token we can say uh so the refresh token so we can say refresh token  equal to token that we have received so this API should be working now once we import this  method so this is imported now and now let's   go and refresh our server dock before that let's  copy this refresh token that it generated so   I have copied it and Let me refresh so  we should see the refresh token here   okay and if I click on the try out if I paste  the token refresh token that I copied previously   click on execute this should be working  but it says internal server error okay   let's see what is the error now uh where it is not  associated with a value it cannot access variable this is this is in the services  file and number 82. line number 82 82 that means cannot access local variable the refresh token  where it is not associated with a value why oh there was actually a type of let me make it correct so this should be fine now if I click on execute in  some issue user token got an   okay so we have renamed it so there  also we need to put the correct name   okay so let's click on the execute again okay  perfect so now this our refresh token API is   also working and we can see the new access  token and this refresh token so if you click   on the execute again you should see your new  refresh token so as VQ is the last character   so if I click on this you can see that qxnm so  now our refresh token API is perfectly working okay so what else left so now we need to create  another API that is user slash me okay okay   so I'm inside the users folder and inside the  routes file okay so here we need to add another   route that is slice me okay so let's say let's  create that so we can say uh router dot post   and we can say slice me you can  also add the get one present matter   uh I mean it will work in both the cases  okay so here I am going to use the same   status code uh not same going to return the  200 status code so I'm just going to say 200 okay and I'm going to return a  response let's not write it just now   so I will write a method called f get user detail okay so this will receive only one  uh argument that is the request and   this request will be coming from Fast API okay request and I can just say return the request dot to user okay  so basically this will be our   way of returning the login user but it might  not be working at this moment so let's let's   try if and see if this is working okay so let  me just refresh this and if I click on try now   internal server you will you will get some  error and if you see the logs authentication   middleware must be installed to access the  request user okay that means we have need to   install this Authentication middleware so let's  do that so for that we need to go to the main   okay and here we need to install the  Authentication middleware okay so this   authentication middleware actually comes from the  Starlet like this so we can just import it from   Starlight middleware authentication middleware  and we can say here you can say uh add middleware app Dot and add a middleware I think yes   add middleware and then we can  say authentic case Sun middleware   and this Authentication middleware will take  another uh thing that will be called backend okay   and this back end that we we need to create okay  so I'm just going to create a JWT authentically since we are using the JWT token so we  will be using the JWT auth Azure backend   so this I will create inside the security  so I can just import it from here   so core dot security import JWT both but  this class is not there so let's go to JWT   let's go to the security and create this  class okay so inside the core security let's get this class JWT auth or okay and this  uh what this class is going to have so actually   this class will have only one method that will  be authenticate okay so as soon as the request   comes to the first API that authenticate method  will be executed and there we need to return the   user if the user is logged in okay so we need  to write our custom method so we can say async   diff authenticate okay so this we need to do  and this by default this receives the connection   or you can say HTTP connection okay so  this method receives the HTTP connection   so I'm just going to create if the user is  not logged in then what we need to return   that means because this will be executed with  every request right and not all the requests   will have the access token so in that case we  need to return something else and that will   be that I am going to call it just so I can say  like uh guest equals to and we need to import a   couple of classes and these classes will come  from the Starlet practice so we can import it   so this classes will be like uh auth credentials  and Unearthed user unauthenticated user okay so   these two classes we need so for this so let's  continue so we can say Earth credentials and   this credences will accept a list and in this  list you can say if the user is authenticated   or not so I'm just going to say unauthorized  okay and then return the unauthenticated user object so whenever we return the guest then  our request will have the information that   it's not uh authenticated and it will have  a when we call the request.user it will have   the unauthenticated user model okay so this is  the now now we need to write the implement the   method so for this I'm just going to check if  our request have the authorization header okay if authorization header is there in the connection so we can say so I am just going to check the reversing if  authorization header note in the connection header   that means HTTP request headers then I will just  return the guest that means we need to we we need   not we should not do anything because this error  is not brilliant that means user is not logged in   if this header is present then we need to extract  the token from there so we can say token equals   to connection dot headers dot get and what we  want to get we want to get uh authorization okay and then authorization  headers so the token will   come in the form of let's say something like this Bearer Bearer then space then token we  need to extract this as because this   is our actual token not this one so for  this we I'm just going to do the split   and split based on the space  and I'm just going to take the   uh last value that is the uh there will be  two value in the list so I'm just going to   take the last one this token okay so now we  have the token and we can check again if we   don't get the token then what should do if there  is no token then we can again return the guest   but if we have the token then we need to  get the user okay so we need to get the user   so user we can get from the token so we need to  write a method to get the user from the token   okay so for that let me create a  method here and this will be uh let me copy and post paste this method   and explain this to you so basically let  me import the other things that is required what we need we need the user model  get DB and Depends okay so from fast API import depends from core Dot not  code .database import get DB from users dot models import user model okay so we have  imported all those things so get current user   What will what it will do so we'll get the token  okay and using this token we will get the payload   in this method that we had created previously and  we will check if the payload is a dictionary okay   if this is not dictionary then we'll return none  that means we don't have any user and if it's a   dictionary then we will check if the ID is there  if there is no idea that means we cannot get the   user and once we have got the ID we will fetch  the user detail and we will return this user   okay this is like uh when we are calling  the method from here we don't have the DB   connection right so for that we can get the  DB connection using the next so we can say DB   equals to next and then we can call the get DB  this will give a session database session okay   so we can get the user from here so we can  say user get user and we need to pass the   token equals to token and again we can  check if not user then return the guest   and if we have the user then we need to return the  path credentials and here we can say authenticated authenticated and we can return the user here so  this this response will be a tuple okay so this   is now implemented in our main dot Pi let's save  it so this is now saved and we have successfully   uh created this one let's go and refresh our  documentation so if I refresh if I click on   try click on execute So currently I'm I'm  not getting any uh response it's returning   but it's returning an empty body so why this is  happening okay so this is happening because of   one reason that is if I go to the routes we are  calling the routes but we are not defining any any   dependency here right so this route particular  route doesn't is not aware about the token   okay so to make it aware uh  about the token what we can do   uh here we can create another router okay so we  have created OneNote we can create a user route   so that means this whatever we Define whenever we  Define a route using this one that means we are   saying that the user has to be authenticated  and how we can make sure that user has to be   authenticated to to do that we need to add one  dependency here one or more than one whatever   you would like to add so we can add dependencies  and this dependencies will depends and this bill   depends upon the oauth 2 scheme so in the security  module if you see the overscrew scheme here we are   calling the token that means this particular route  will depend upon this token that means it should   receive its this because the road should have  a token okay and that must be generated using   this URL okay so this is some things security  related things so let me uh imported from core   dot security import and what we are  going to report or Earth to scheme   okay so this will depend upon the uh or two scheme  and we need a another dependency that is we also   need to extract the user right so once the request  comes first we will make sure that user has the   token and second we will uh in stack the user from  the uh sorry we will extract the token from the   request NB Bill uh add the user into the request  so for that we can add the dependency get current   user so we can say get current user like this  so now whenever a request comes using this   router this will help the user and this will  make sure request has a token okay so let's   change the router to user router okay and let's  refresh now okay so currently it's not there   because we have not added this user router in  our application so we can do that by saying   uh user router result already there we can  change it to guest router actually guest   router and we can say user router so let me copy  sorry let me copy and paste there guess the router   so this would be fine now so if I refresh you  should see the URL that needs the authentication   uh lock is there right so that means to  access this URL you need to provide the   uh token so if I uh provide the token by saying  DB uh let me let me see something is wrong I guess security [Music] get current user DB equals to none AP question and it shouldn't  be asking about the DB this depends upon both two schemes and this TV  payload so actually this is coming from here so if I remove this and if I  refresh so you can see the lock here   okay and if I try it okay without logging in you  will see not authorized so that means to access   this particular route we need to be authorized  so to get authorized we can say like here admin   oh sorry it was very quick so once we have  added that right dependency we should see   our Thrice button here so from here uh we need  to login to access any URL that has this lock   okay so to login we can click on the button and we  can enter our username and password so admin test   dot com and we can say password  oh sorry something is suggesting this is making it very hard I don't know why okay let me let me open this channel in  another browser why this is happening we saved choose my own password  okay so admin at the redtest.com and   admin at one two three if I click on authorize  you can see that I am logged in and if I close   this one and if I go to this URL not know  if I execute I should see the user details   okay so now this particular URL is but you can  see that uh currently I can see the password as   well password Harris as well but I don't want  that right so for that uh what I'm going to do   in the me I'm just going to uh return add a  response model and this will be user response   so using this response model you can Define  what are the fields that you want to return   so I have I don't have any file called  responses so I'm just going to create   a responses Dot py and here I am just going to  copy and paste the response user response class   okay so it's this one so here I am saying that  from attribute true that means from the model   from attribute means from model I'm just going  to pick the fields and arbitrary arbitrarily   type allowed that means here I am adding the date  time right so this is not coming from the typing   or rep identity right so this is an arbitrary type  so I'm just saying that allow this kind of things   also okay so that's why I have added these two  configuration and let's uh import this so we can   say like from uh users total responses import  user response I don't need this current users   and I this is important now and let's save this  and if I execute this you should see only limited   fields that I have allowed there that is ID  first name last name email and registered it   okay so if I go to uh this response class  you can see these five fields are allowed   okay so this means like we have  successfully completed our this   tutorial we have created a users API that  can be used to create a new user account   okay we have created a slash Earth slash  token that can be used to generate a new   token and auth slash replace can be used to  refresh the token because your token experts   in every 60 minutes right so you need a new token  in every 60 60 minutes so in your front end you   can put a logic like after let's say 55 minutes  or 58 minutes this URL will be called and it will   get a new token and then we have created slice  user slash me so this slice you just slash me   is basically uh getting the token from getting the  user detail from the token that you are passing in   the request this is not directly fetching from  the database okay and anywhere using this uh   using this method so you can just accept the  request in your URL and you can pass to your   services and wherever you want to use the user  detail logged in user detail so you will be   having those so I hope this uh this makes sense  to you and thank you so much thank you so much for   watching this video I will uh put this code on a  GitHub and I will add the link in the description   okay and if you like this video course  I would request you to like and share   And subscribe the channel this keeps me motivated  to create more videos like this thank you so much
Info
Channel: Describly
Views: 11,893
Rating: undefined out of 5
Keywords: FastAPI, FastAPI Authentication, FastAPI JWT, User Registration, Refresh Token, Connection Pooling, How to integrate JWT in FastApi, How to create refresh token api in FastApi, Authentication in FastApi, FastAPI Swagger, Python Framework, Python, User Login, FastAPI Response, FastAPI Configuration, SQLAlchemy Connection Pooling
Id: z3nwf7wGdUw
Channel Id: undefined
Length: 79min 42sec (4782 seconds)
Published: Sat Sep 09 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.