JWT Authentication (Protect Endpoints with HTTP Bearer Auth) - FastAPI Beyond CRUD (Part 10)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up everyone welcome back now that we've been able to give our users access to our application by providing them with tokens we are going to be implementing a way of limiting access to those users who do not have tokens so what shall happen is whenever a user is making a request to some protected endpoints in our API they'll need to provide their token within an authorization header and this is where HTTP be tication comes in so when passing our token we want to go ahead and provide our token in the form of Bearer and then the token so they give the word Bearer as the scheme and then our token shall be the set of crti that they will provide to access our endpoint and basing on that we shall decod our token and then carry out any other forms of validation or authorization that you may need within our app to do this we're going to go within our o folder we're going to create a new file and we're going to call it dependencies P so inside our dependencies we're going to begin by importing the special class that is going to allow us to carry out our HTTP bar authentication so that is going to be from past API do security shall import our HTTP Bearer class and this HTTP Bearer class is going to be the special class to allow us get to protect an end point and make it only be access when someone provides their token in the form of Bearer and then the token so the way we use it is by creating an instance of this class and then providing it as a dependency within the path Handler of that specific function and once you've been able to get that then what we shall do is to access the HTTP authorization credentials and using those credentials shall give us access to the credentials scheme and the credentials credentials which is going to be our token in that case so let's go ahead and be able to do that so I'll just come right here and then we shall create a class which which we're going to call rjt bar now I'm just simply going to come and call this the access token Bearer because it's going to be one to allow us to validate our access token so I'll just come right here and say this is going to be our access token Bearer and what this class is going to be is a child class or one that's going to inherit from the HTTP bar class what I'm going to do is to pass this for now and we shall make use of it to protect all those end points we are going to access with our access tokens so we shall go to our routes for books because those are the ones that are to carry out quir on our book resources and we're going to Simply go ahead and protect them so the way going to protect them is by first of all importing our class I'll say from our source. o. dependencies we shall import our access token beor and once we've got our access Token Bar now create the object out of that class so I'll just come right here and say uh security or let's just say uh let's just actually just call it the access token Bearer so just come right here and say this is going to be access toin bar and this is going to be an object of type access token Bearer once you've got access to this object then you shall provide it as a dependency to our path Handler so what you're going to do is to go with our path Handler for getting all books and then we shall provide another parameter which is going to be our so let's just call it security or let's just call it credentials which is our user details so in this case our user details are going to be uh going to be first of all authorization credentials just like we saw in the other example but it will be a dependency from the object that we created out of that class so this is going to be our access token bear me forat so that we make things a little bit more organized so once we've got that then that marks this as a protected end point in fact if we try to access it then we shall see that it's going to require us to provide our token so I'm going to go ahead and save and when I save when you head over back to our rest Forks right here when you try to get all books for now we can get them without having to authenticate but when we provide this dependency right here we're going to need to provide our authorization header for us to go ahead and make this request so to do that we're going to go within our headers and then we shall add an item and this is going to be our authorization headers so I'll come right here and say authorization and our authorization will have a value so our value is going to be in this case be and then the token in this case our token is going to be the access token that we got from our login request so I'll come right here where I go to our token pair create a new access token and then I'll copy our access token right here then I'll copy it and then that's what I'll provide to get all our books so I'll just provide it and then we can have access to our books so that is just one basic way of us protecting our books but just in case we need to carry out any other forms of authorization or any other forms of protection what we need to do is to go ahead and override that class so that we can check for other things or other criteria that we may use to allow access to a specific Endo so let us go ahead and look at how we can do that when you head over back to our code within our dependencies when you check the source code for our htb class we shall notice that this is going to have the dander init method as well as the call method now the call method is going to be the main method that's going to allow us to access our credentials and carry out whatever we need to do in forms of authorization so what you can see here is it works in a way that it gets the authorization header that we provided and splits it into the scheme which is the bearer part of our authorization header and then the credential so the credentials in this case are going to be the token just like we see right here after doing that it will check if we have not yet provided those and then we raise not authenticated so in case we delete this and try to make the request again of course shall see that we are not authenticated and if they exist then it will go ahead and check if the be is valid and then it return valid authorization credential so that's just how it works but in case we need to add other checks then we need to go ahead and over that method so for us to do that I'll close this what we're going to do is to first of all redefine the D init method of this class so shall just come right and say def then in it and in this case we're going to provide self as well as one so this is going to be one parameter or one argument that's going to be created with this objects and that is going to be the auto error so I'll just come right here and say Auto error so our Auto error is going to Simply Be an attribute to this class that's going to determine the behavior of this class when an error occurs so when you have an error first API is going to return that error but in case we set this to false then first API is going to not return that error but rather provide for us none as the return value of that specific error so if an error occurs we are getting the error in case Auto error is true and in case we do not get the error then none is what we're going to get so what I'm going to do is to set this to true so that we can get the real error that has happened and then we shall just simply go ahead and override the unit method so we shall say super do unit so this is going to call the init method of our parent class which is our HTTP bar CL so we shall say d in it and in this case we shall go ahead and set our Auto error so this is going to be our Auto error so once that is done then we're going to go ahead and override the D call methods we shall just come here and say a sync death and in this case we shall go ahead and access the Dand call method so this is going to have a lot of attributes but it to return our HTTP authorization credentials or n in case they do not in case they are not got so once we have these credentials we can just simply say that the return of this is going to be our credential so I'm just going to call them credits for short and inside here is where we can split them and then try to do whatever I want with them so in this case I want to check if the provided token is an actual access token so to begin I'll have to just go ahead and split this so I'll say print cedes so our cred is going to be CED do so let's just access the scheme for now and then we can also get to access the the credentials part which is going to have our token so I'll just come right here and say print this is going to be creds do credentials so this will provide for us our token then once we've been able to do all that we shall just simply go ahead and return our creds so in case we try to make a request again we shall see what shall be logged so I'll head over back to our rest forx I provide our header which shall be authorization and then we shall provide the value of that header as be and then our token so I'll go ahead and provide our token I'll copy the token that we have right here and then I'll simply go ahead and provide it in here so if we save and send this request shall see that we can now access our resources but if we go within our terminal then what shall be locked is going to be our token so we're going to have our Bearer which is our scheme in this case as well as our token so our token in this case is going to be our token so now we can access our token so once we've been able to do this then let's go ahead and basically decode our token and find out if our token is valid so we wrote a specific method or a specific function which is called which is within it and is called a decode token so this is going to do is to decode the token get the data out of the token and check if whatever want out of this token is valid now what we want to do is to check if this token is a valid access token to do that we're going to first of all import this function so shall go the top here and say from uh Source or in this case it's going to be within our U so shall say froms we shall go ahead and import our decode token function and I'm going to create one function to check if our valid or if our token is valid so shall just go ahead and call that our validate token or let's say this is going to be a token valid because it's going to return our bullion so shall say token valid and this is going to take in our token but because it's a method it will take itself so we shall have a token and then this token is going to be a string but we shall return a Boolean in case it's valid or not so we can actually return a Boolean of true or false depending on whether it's valid or not so I'll just come right in here and say that we're going to access our token data by using our decode token function so in this case shall say the code token and then this will take in our token and once we' provided our token then the next thing is going to be for us to return true or false in case this token is valid so shall just come right here remember that this function is going to return n in case our token is not valid so we can do something like if our token data is not none then we can go ahead and return true else we can return false so in this case we can return true and in this case we can say else uh return false we can also summarize this into something like return true in case our token data is not n else false which we can do like by doing something like can just come and say so this is going to check if our token is valid once we've been able to do this now let's go ahead and uh authorize our users or check if our user is valid they providing a valid access token so to do this our token is going to be form within credentials. credential so I'll go ahead and simply get rid of this and then our token is going to be creds do credentials so this shall give us access to our token so shall check if our token is valid so shall say if not so in this case not token valid then we shall throw the exception so we shall say if not token valid then we shall raise an error so this is going to be raise an HTTP exception but remember this shall be access via self so we shall say self dot token valid and in this case we shall raise an HTTP exception so I'll go to operate here and say from first API dot exceptions we are going to go ahead and import the HTTP exception class so once we've imported that then we're simply going to go ahead and say that we are going to raise our HTTP exception and our status code is going to be equal to status so we're going to have to import this so that top right here and say that we're going to import our status and once we've imported that then we need to access the the HTTP 43 forbidden because you don't want them to access this so we're going to come right here and say that our detail is going to be equal to invalid so that shall be thrown in case we get any errors when decoding our token so this is going to be invalid or expired token and then it will return the credentials just in case they exist but one thing we also need to check since this is our access Bearer token so we need to go ahead and check if it's a valid token so the way we're going to do that is by simply decoding our token and getting our token data so we're going to come right here and say that our token data is going to be equal to the code token and in our case we shall basically get access to the Token data from our token once you've got the token data then I'm just simply going to go ahead and check if our token data refresh property or refresh attribute is false is true then that will be marked as a refresh token so shall say something like if token data so in this case token data then in this case shall get the refresh property if token data refresh meaning this is a refresh token then we are going to raise an HTTP exception but shall tell them to provide an access token so in this case we shall provide we shall raise the exception but the exception is going to be please provide a valid access token so in this case shall say PR provide an access token so that's just the check that we have done for our access tokens now we're going to also look at how we shall be verifying whether our token is a refresh token it's going to almost be the same way so shall look at how we do that so just in case we have been able to do that then now we can go ahead and protect the rest of the end point so I'll head over to our out for books and then what I'll do is to just copy this dependency and provide it within our handlers for the remaining end points so I'll just copy this and then go ahead and inject it within our routes so just come and provide it right there I'll do the same thing for this path so just come right here and say that we are going to also have it in there so I format our code and then we can go ahead and simply return or inject this again then I'll go ahead and do the same thing for our delete book so I provide it in there m our code and this is how it's going to look now another important thing that you can do is to Simply return instead of returning the token we can go ahead and simply get the the user details so instead of returning arit just like we did here what you can do is to return the token data we get out of the coding the token so I'll just come right here and say we're going to return our token data so that means we can get access to the user ID and by doing so we can get access to the user details so I'll go ahead and save so once that is done then you can simply go ahead and access the user details inside our routes by simply printing them out so when you go back to side where we injected our user details in case we want to access our user details if I say print user details then this shall go ahead and provide our user details so I'll save and then when you go back to our Forks here and try to make that request in our time you know we shall see that we can access our user details so in this case we know that our user is J their user ID is this and the rest of the other things that are related to this specific token so by doing so we've been able to protect our tokens now in the next video we going to be looking at how we can generate new access tokens to allow users to extend their session within our application thanks for watching and I'll see you in the next video bye
Info
Channel: Ssali Jonathan
Views: 302
Rating: undefined out of 5
Keywords: fastapi, fastapi jwt auth, jwt authentication fastapi, api development, rest api
Id: 9mx6LojqNCQ
Channel Id: undefined
Length: 19min 38sec (1178 seconds)
Published: Tue Jun 18 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.