Node.js API Authentication With JWT

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] coding dojo is a programming school that turns beginners into developers in only 14 weeks over 90% of their grads land jobs within three months of graduating often making over seventy K per year to learn more visit coding dojo com or click the link in the description below hey guys I have a request from one of my patrons to do a video on note authentication with JSON web tokens or JWT and these tokens are used to protect routes in an API that way you can add authentication to fetch a token and then you can make requests with that token to access protected routes so if you have a full stack application where you have like no no to API on the backend and then react on the front-end you can make your request to login you know do all the login stuff and then get the token back save that in local storage or cookies or wherever you want to save it locally and then you can use that token to make requests to protected routes like let's say to create a blog post or something like that alright now we're not going to build a complete API here we're not going to implement passport or authentication or anything like that we're just gonna have like a mock user my goal is to just show you how to protect routes and then how to get the token and use that token to access the route alright so it's kind of an off-the-cuff video we're using postman to make our requests this is a now a standalone best standalone program it was a Chrome extension I believe it's deprecated as a Chrome extension now so that's what we'll be using to make our requests we're using vs code for a text editor and i'm using my vs code terminal here so I have an empty folder called node auth API so if you want to follow along just create a folder and then we're gonna do an NPM in it to create a package dot Jason I'll just go through this description I'll just say JWT example and I'm gonna use a pas for the entry point and then just enter through the rest all right so now it will do is install our dependencies so npm install we're just gonna have Express and jason web token all one word okay i'm also going to install node lawn because that will just continuously watch our applications so we don't have to restart it - you know if we make changes or whatever and we're going to install that globally so we're going to do npm install - G and then node Mon alright and then once we do that let's clear that up we're going to create our app dot JS file and let's open that file up I'm just being fancy with the terminal of course you can create it up here so in our app j/s let's go ahead and bring in Express okay and let's see we also want to bring in Jason web token so that's going to come in as well name a JWT and that's going to come in as jason web token then we want to initialize our app variable with express okay and I'm just going to create a just like a welcome route for the index actually we'll do slash API and we'll put a arrow function here and of course we need our request response all right and then in here all I'm gonna do is do a res dot jason and we're gonna send along a message and we're just gonna say welcome to the api okay so there's a simple route and we're going to now listen I'm gonna have our server listen on port 5,000 oops and then we'll just do our console log server started on 5,000 all right so let's save that and let's run node Mon down here in the terminal so our server started now we should be able to make a request to this slash API and we should get that message back so let's say HTTP do I have it here HTTP localhost 5,000 slash API make sure it's a get request and send and we get welcome to the API so so far so good now I want to create a route that I want to protect so let's do an app dot post - slash API slash posts and say request Raz and obviously we're not really gonna create a post or anything we're not using a database I'm just gonna do a res dot JSON and we'll just do the end result which will be a message that says post created ok so we should be able to to make that we haven't protected anything yet so we should be able to make a post request to API slash posts and we get post created alright so now we're gonna start to implement our JSON web token we need a way to get the token and we're gonna create a route for that so that's gonna be a login route so let's say post slash API slash login alright let's put our request/response and inside here what we want to do is we want to call JWT dot sign now I'm actually going to open up the documentation here and you can do this either synchronously or asynchronously if you're doing it synchronously you can set a variable to JWT sign pass in your payload and then a secret key which can be whatever and then you can go ahead and use that or you can do what we're going to do and we're going to use we're just going to use a callback function we're going to do it asynchronously so let's do JWT sign I forgot to create a user so we're just going to create a mock user now usually you would make a request to this login and you'd be sending your username and password you'd go through all your your authentication stuff here with your database and then you get your user back so we're gonna skip right to getting the user back so I'll say ID 1 user name Brad and let's do email Brad at Gmail all right so we have our user and then what I'm gonna do is I'm going to send this along as the payload so this will be say user user so payload next parameter will be the secret key and you can see over here JWT sign they sent the payload here and then there's the secret key so that can be whatever alright and then since we're using the asynchronous version we're gonna go ahead and put a call back or an arrow function in this case and this will take in an error if there is one and then it'll take the token it'll give us the token alright so then what we want to do is just send the response so res dot Jason and we're going to send a long token and we're gonna send the token all right we can even do this via six tile and get rid of that same thing here since these are both the same we can just do like that all right and yeah let's save so now we'll try and log in so we'll go to a post request to API slash login and send and there it is so we get our token back okay so this token contains all the information we need to make a request to a protected route which we don't have yet all right so let's go ahead and go to our route we want to protect which is this right here this posts and we're just going to add in right here a middleware function called verify token like that okay and then we need to create that function so we'll go down here and let's just say verify token and function verify token all right so this is going to take in this is actually a middleware function it's going to take in a request response and next so basically it's gonna run we want to do what we want and then call Next to proceed okay so first thing we want to do is we want to get the auth header value so when we send our token we want to send it in the header okay and we want to send it as the authorization value so I'm going to create a variable here we're gonna call it bearer bearer header and we're gonna set it to request dot headers and then we want the authorization part of it so authorization like that and that should give us the bear header I'm sorry that the actual token now the way that this token is going to be formatted let's say format of token so it's a it's what's called a bearer token so it's gonna look like this authorization it's gonna have the word bearer like that and then it's gonna be the token so we'll say access token all right so it's gonna look like that and then we need to pull the token out of it so we need to do a couple things down here so first thing we're gonna do is check to see if it's not undefined so say check if bear I can never spell this while I'm talking B error is undefined so we'll say if and we're gonna use type of so if typeof bearer header is not equal to undefined then we want to continue else then it's gonna be forbidden all right and we can actually just send a 403 status so if we say res dot send status I mean you can do a dot jason if you want resin and put your own message here but I'm just gonna send a 403 all right now let's just try that out so we'll save that and we're gonna go and try to make a request to API post which has the verify token middleware and if we don't send the token we should get the 403 status so I'm going to open a new tab and go to http let's go to localhost 5,000 API posts make sure it's a post request and send and it gives us back forbidden okay so that's exactly what we want we can't access it without that - without a token so let's go back into the verify token function and we need to basically take the token out of the bearer space token so what we'll do is we're gonna split out the space because it's going to be Bearer the word bearer space and then the token so I'm going to say Const there are equals and then we want the bearer header and we're going to do dot split what dot split does is it turns a string into an array and you can put here what you want to split it by and it's going to be a space so it's going to look at this Bearer space token and it's going to separate the two by a space and turn it into an array so in that case this will be that the second part of the other second value in the array which has a 1 index because arrays are zero base so this would be 0 this would be 1 so let's go on the next line and let's say get token from array so we'll say Const bearer token and set that to there with the index of 1 all right then we want to actually set the token by simply saying request dot token and setting that to the bearer token okay and then we simply want to call the next middleware by saying next and that's it that's our verify token function so let's go ahead and save that let me just double check this that should be good so now what we need to do is when we enter this protected route here API post we need to verify the token okay and let me actually just pull up the documentation for that so let's see so we already did the sign let's see right here JWT verify token right here verify token and then we also want to pass in that secret key as a parameter but we're gonna do it the asynchronous way like this and we should be able to get the data the payload that we passed in so when we logged in right here we passed in the user we should be able to get that data as well so let's go to our post route here and let's go right here and we'll say JWT dot verify and inside here we're gonna pass in the token now that token is now in that request object so we can say request token and then we want our secret key and then we want a callback or an arrow function in this case and this is going to take in two things it's going to take an error and then the data I'm going to call this off data because it's basically going to be our authentication data our user the ID username and email and then inside this verify will first check for an error so we'll say if there is an error then let's go ahead and send that 403 status so whereas dot send status and we're gonna send whoops I'm gonna send 403 and let's do else then we're gonna take this res dot Jason right here and we're going to just move this up into the else and we'll send the message post created let's also send the auth data okay so we'll get the message post created we'll get the auth data we should also get the timestamp that this was created I believe yeah let's just try that so we'll save we'll go back to post man now if we try to make a request here again we get forbidden that's expected we need to include our token so the token we got when we logged in now if you had a front-end app a front-end client with like let's say react or something or or whatever vanilla JavaScript you would save this token in local storage you could also use cookies but that's not really recommended anymore you want to use local storage and then when you want to make a request to a protected route you want to send in a header value for authorization so we'll show you this will say authorization and we're gonna say in here there are space and then the token okay so let's try this we'll go ahead and click send and there we go post created we get our message we get our auth data which includes the payload that we sent here okay so when we did JWT sign we sent the user that's what we're getting here and then we get this I 80 which is issue issue that I think does this stand for pretty sure it's issued at yeah issue that so you can include a timestamp but if you don't it'll do it'll give you this issue that time stamp so now you can continue to make this request as long as you have that header that token ok present in your header this here if I go ahead and I uncheck this and I don't send this header value along with it we get forbidden ok if I were to change this in any way like let's just put a 1 here and send we get forbidden ok so it has to be this exact token now another thing we can do is we can set in expiration if we want this token to not last forever we can do that so let's go to see I can make this smaller here we want to go to the login where we do the sign and we just want to put in some options right here so we'll put in an object like that and then in here we're gonna say expires in and then we can say we can do like 30s for 30 seconds we can do minutes and this is all in the documentation so these are all the options you can use and expires in is one of those so you can do like two days you can do 10 hours you can use all those different formats so let's do 30 seconds all right now we're gonna have to make another request to login to get a new token so what we'll do is let's get rid of that and then we'll go back to our login and let's send so now we get a new token notice it's a little bigger because it now includes that expiration so we'll copy you will go back to posts put in our authorization and we'll say there are space and then paste in our token and send it works okay I'm gonna keep trying and it should expire within 30 seconds so it should not work pretty soon and you can see it's actually one of the values exp so this is issued at an expiration send again and now it's forbidden okay because it expired so you can do that as well alright so I know this isn't like the most put together thing but hopefully this gives you an idea of how to protect your routes how to get a token and then how to use that token to access protected routes and obviously we're using postman as our client but you could just as well have a react application or an angular application and use the HTTP client there and just send along your authorization in the header with the token alright first login and so on but of course you're gonna want to have a form submitted to login and do your magic here to add to authenticate the user get that user and then include that user here not just create one like this this is just a mock up alright so hopefully you guys enjoyed this and hopefully it was kind of it was somewhat clear and that's it thanks for watching guys and I will see you next time coding dojo is a programming school that turns beginners into developers in only 14 weeks if you're serious about landing a career in tech but lack the formal education or background coding dojo will get you there in no time with over 3,000 graduates to date over 90% of their grads land jobs within three months of graduating often making over seventy K per year at tech firms of all sizes from companies like Google to local startups to learn more visit coding dojo com or click the link in the description below
Info
Channel: Traversy Media
Views: 452,970
Rating: 4.9334083 out of 5
Keywords: node.js jwt, node.js api, node.js json web token, jwt, json web token, node authentication, node token, token authentication, node auth
Id: 7nafaH9SddU
Channel Id: undefined
Length: 23min 0sec (1380 seconds)
Published: Thu Dec 21 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.