Generating Authentication Tokens (Django Rest framework TokenAuthentication)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so as I talked about a couple of videos ago in the when I talk about token authentication we are going to be using django token authentication to authenticate users on the server so if they're using a mobile app Doupe Doupe Doupe do they got their phone they are gonna send a request to the server get a token and then once they have that token they can access any of the other data on the server so there's a there's a couple things we can leverage with Django here Django has kind of a built in system for generating these tokens and it also has some built in URLs that we can take advantage of to return the tokens to the user when they enter their username and password for example so there's going to be kind of three sort of steps to this procedure number one is we need to create a database table that holds the tokens so it'll be you know a database table literally called tokens with each user in it then they have their own unique token in it it's gonna have a foreign key relationship to the account table then every time I user logs in a token is generated so if they visit the URL like you know your domain slash API slash account slash login it's gonna generate an authentication token if they log in with their correct email and password so basically it's just gonna generate a token put it into the token table and then return that token to the user through the request then once they have that token they can attach it to the header of any of the other requests that they make to the server and we have some other built-in Django stuff that we're gonna implement for permissions and restrictions basically that will check to see if that token is there and if that token matches the email that they they set they are signed in with so a bunch of stuff going on and we're gonna take a look at the guide first because there's like there's a there's a guide on the documentation that actually outlines this pretty well so we're in the Django Doc's here and I'm in API guide slash authentication so you could just click here go to authentication which is what I'm on and I'm in this at the section labeled how authentication is determined and I actually I encourage you to just read like at least read the beginning of this doc so it says authentication just read down to like down to like here like read this stuff basically what it says is how authentication is determined on the server and then it goes on to talk about the different that you could be authenticated so first of all it says how authentication is determined there's a bunch of different ways so this basic authentication token authentication session remote user custom authentication so what we're going to be using is token authentication and if you go down to the token authentication section it says down here that this is great for native desktop and mobile clients so this is exists for we're doing mobile clients so if you go up to the top there's kind of a basic procedure that you need to follow it says that setting the authentication scheme so we need to add this rest framework declaration to the settings py file and then we need to define the authentication back-end that we're going to be using in that case and this in this example that they're showing the doc they're using basic authentication and session authentication but we're going to be using token authentication so let's let's follow the first step so I'm going to copy this go to our project I have a bunch of stuff open I'm going to close it all I'm going to minimize this so we can get a good look at what's happening here I'm gonna expand my site go into settings py and maybe just below the installed apps I'm gonna paste in that rest framework declaration and delete the second session authentication and I'm gonna change this to token authentication because that's the only type of authentication we are going to be using on the server and basically what this does by declaring this Django knows that if I set any if I set an is authenticated permission to any of the views which you'll see later on it knows that I'm talking about token authentication and it knows to look for that token in the header of the request that probably made no sense to you but I'm gonna revisit this later when we actually go through that process so that you'll you'll remember what I said so let's go back to the docs here and now it just talks about the different types of views that you can use so here the first view is a class based view we are we're gonna be using a class based view I think one class based view later on in the course but not in this video we are going to be focusing mostly on function based views so just like we've been doing you define a function view and then returns stuff through a response so here's actually what I was talking about by the permission classes so if you'll notice there's a couple annotations here the authentication class is annotation and the permission class is annotation the permission class is annotation you can specify what kind of permissions you need to be able to see any particular view so like in the case of this app we're using token authentication so if I pass the is authenticated class which is a prebuilt to class you can see it's imported from the rest framework permissions package it's a pre-built pre-built class and what it does is it looks into your settings py file and it looks to see what rest framework default authentication classes you've defined here so because we've defined token authentication that means that this is authenticated class we'll say okay he's defined token authentication let's see if there's a token in the request and then if there is a token and it's valid it will allow them to see the view otherwise it will return a response that says you don't have permission to view this so that's a really really cool thing about Django like there's just all these pre-built functions that do so much work for you behind the scenes and you don't have to do anything really so that's what that is authenticated class will do and we're going to be using that the authentication classes are the different types of authentication so that's but that basically tells the permission class which type of authentication class you're going to use so in our case we won't have these two we're going to have token authentication obviously so that is that's the explanation now let's let's get to it so let's go down to token authentication it looks like the the first step here it tells us to do is that we need to add rest framework auth token to the installed apps so let's do that let's go to our settings py file addressed framework auth token pressing ctrl s to save that and then it tells you that we need to migrate because it's going to generate a bunch of stuff so this is actually going to generate that tokens table that I talked about I'm pretty sure so managed up py migrates let's see what it does looks like it generates an auth token table I believe I'll do make migrations just to make sure if it managed up py make migrations just to make sure that there's nothing that needs to be applied no we're good to go and now managed up py run that server so now we're pretty much done with the docks because now it's up to us to implement the functionality that we need so I'm gonna go to our project and so let's talk about as a plane going over by so I'm just gonna hold on a sec here wait for it to pass okay the planes pretty much gone so there's two situations where we need to generate a token number one is when a user registers when a user registers just like we did in the previous video if I was to register a new user we get like we get a response I guess I'll just just to show you I'll just generate a new user generating a new user so we get this response we also want to generate a token and return that token in the response that way when they register right away they can start using the app because they'll have access to that token so that's the first one the next one is going to be when a user logs in so that'll look like it'll look kind of like this if I would just copy this URL suppose they've already registered obviously we need to create a URL where they can log in and pass their username and password so it's gonna be a post request they're getting or they'll pass their email and password it'll be email you know whatever their email is and then their password and whatever their password is and then it should return a response that holds that token we don't need to return anything else we can just return the token because that's essentially what it means to be authenticated once they have that token they can use the REST API to its full functionality and do whatever they want so so that's what we're gonna work on so registration we want to generate a token and return it login we want to return a token because they should already have one that's been generated and if they didn't we can check to make sure all right so let's go into account API actually not API we want to go into account models because when a user when a new account is created we want to generate that token so a good place to do that is just in the model we can create a post save receiver that will generate a token when a new user object is saved to the database so coming up to the top here I need to do some imports from Jango dot whoops I need from from Jango not form from Django Kampf import settings so we can get access to actually I don't know if we need settings but anyway from Django DB models dot signals import post save we definitely need that from Django dispatch import receiver from rest framework dot auth token models import token so now after we have those imports I'm going to scroll down and create that post save receiver so down at the bottom I'm gonna write at receiver this is gonna be a post save receiver the sender is gonna be yes that's what I needed the settings for I thought I needed that the auth user model and then define it so it creates auth token the name doesn't matter but I'm just going to call it create the auth token the sender which is going to be the account that's going to be saved to the database instance can be none created equals false and then keyword arguments so then I just want to say if created if a user object is created or sorry if I count object is created and inserted and saved into the database I want to generate a token so token objects dot create and I want to say user equals instance that's gonna be it so now every single time a user is registered to the server a token will be generated and we can test this so I'll go to the server I'm going to log in and go to the admin I'm gonna delete these two test emails that I created earlier just going to delete these also notice if I go to home there's now a tokens table and inside the tokens table there is nothing so what I want to do is I want to generate tokens through registration so I can just you know I can use this same user because I just deleted it I'll click enter that means they were registered now let's go to the token table and now there is that token with that user associated with it so this this user now has an authentication token that they can query to use the API well I guess we don't have the view setup yet but we actually do have a toke and so now you're probably wondering well what do we do about these other users well I'm gonna delete these two because we don't need them they were just for testing anyway the only problem here is going to be this one so we we do need a way to generate a token for the admin user and I actually recommend just just deleting everybody and then creating a new super user that way you're you're still going to use the systems that are in place you're not kind of overriding the system there are ways to generate a token through the admin so I think if you if you browse through here I remember I saw something where you could generate a token through the admin or like kind of manually but I mean I think you know I would just as soon just delete everybody so I'm just gonna actually delete Mitch at Tavian dossier which is the super user and I'm just gonna create a new super well I just delete the wrong one oh well let's delete them all or deleting them all goodbye now everybody is deleted and I'm going to create a new super user so Python managed py create super user and I'm going to go through the process of creating a new super user so Mitch my password and I'm going to run the server and go back to the admin now I should have there's that new super user and if I go to the token table I have a token for that user and if I was to register in your user and I go back to the token table there's another token generated so now we have our whole system is in place and it's working correctly so now the next situation we have we have it working for registration now the next situation is getting it working when a user logs in so we need to generate a token when a user logs in oh actually I almost forgot we also need to return that token through the response because remember when we're registering we want to return that so I'm going to account views in the API section and I want to query the token that has been generated so in the right token equals token objects dot get and do user equals account and then do dot key to get that token and then data token equals token and that will return it and of course I still need to import token from the rest framework so from rest framework dot auth token dot models import token there we go so now if we user registers it when I save it the token will be generated and then we can return that token right here to the response so now we're ready to work on logging in so what happens when a user logs in how do we generate a token when a user logs in this is actually very simple because of the Django rest framework some built-in functionality so I'm coming into our URL spy and I'm actually just going to copy this change this URL to login and this view is going to be obtain auth token so it's an obtained auth token view and this is going to be login and of course I need to import that view so from rest framework dot auth token views import obtain auth token so what this is gonna do is it's a built in django view what it does is it looks for the user model for your project so if I go into my site go into settings and I scroll down and I look for the auth user model which is referencing my account model it looks for that and it asks for the required parameters to login a user based on that user model so in our case that means the username or the email and the password so all I need to do is send a request to this URL containing the email and the password and it will return it will generate a token upon successful login so I'll show you what I mean first let's actually test the registration because we changed something there because now it should return a token so I have a new email new username i'm gonna click send there's the token being returned so that's working good now let's try to login so Mitch at Tavian CA is one of the users his password is password let's click send I believe that's all I need and see oh right so this is kind of a weird thing about Django so it says username this field is required so because by default Django the Django user model uses the field username to log in but we have overridden that and set the username field to the email but by default all of kind of the prepackaged views still use that username field name I guess I would say so I still need to declare user name as the key even though I'm passing the email it's kind of a weird thing I really don't like this about Django it's it's a very confusing thing but just kind of know that by default generally Django assumes you're gonna log in with a username but we've overridden that to use the email so you still have to use the username key so now if I click send it will return that token so yeah and I think it generates a new token every time you login looks like no that one's the same so every time you log in you will return the same token but the point of it all is that you do generate a token and and the view is kind of pre-built and you don't have to do very much so now the next thing we're going to work on is permissions so as I talked about in the beginning of the video and we took a look at the Django documentation if we take a look at the view examples here you have to pass a permission class we're going to be using the is authenticated class and we need to be passing authentication classes also in this other annotation and that's going to restrict access basically so it will if if a user isn't authenticated through the method that's declared through the authentication class then they won't have access to the view and that's how we restrict users who don't have a valid token to use the REST API on the server you
Info
Channel: CodingWithMitch
Views: 64,044
Rating: 4.8745947 out of 5
Keywords: django rest-framework, django rest framework, django rest framework tutorial, django rest api, django rest token authentication, django rest token authentication tutorial, django rest framework token authentication, django rest framework token authentication tutorial, token based authentication django rest framework, django token based authentication example, token authentication django example, token authentication django rest framework
Id: Wq6JqXqOzCE
Channel Id: undefined
Length: 17min 28sec (1048 seconds)
Published: Thu Jul 18 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.