JWT - JSON Web Token Crash Course (NodeJS & Postgres)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
JWT or jot is an internet standard for creating JSON based access tokens that assert some number of claims in the token itself so that it is completely stateless in this video I want to talk about the following I want to discuss all the good old session based authentication because that's what existed before JWT came into the picture it had some limitation people shy away from it and readability was invented to solve certain problem KJV 8 ability obviously came with their own problems that which we're gonna address in this video and the second thing we're gonna discuss its durability based authentication and what is it some examples how does it really work and then we're gonna talk about refresh token a workaround in my opinion to solve some flaw and JWT some people home like that but that's the truth alright and we're going to talk about asymmetric durability another factor of JWT encryption algorithm for the signature we're gonna talk about that it's very very critical people know who used the ability to use that especially in a microservices architecture we're gonna talk about code example people favorite part where we're gonna show an full-fledged application using a session based i'm using Postgres and express i'm gonna provide the source code that i wrote and I'm gonna write using readability so rewrite it in a bit using JWT and can use a refresh token access tokens all that stuff right so and as I talk you should start seeing some time codes where you can jump into the interesting part of the video you don't have to watch the whole thing obviously and finally pros and cons of JIT ability because guess what nothing is software engineering it's perfect everything has a pros and cons and you as an engineer you assess your use case and pick what is best for you and nothing else right there never get attached to a technology alright if you're interested stay tuned if you new here welcome my name is Hussein in this channel we discuss all sorts of back-end engineering really and if you're interested to become a better software engineer consider subscribing and hit that Bell icon so you get notified every time I upload a new video that's it let's just jump into chart first thing we're gonna talk about session based author authentication good old stuff we have a beautiful database here I have reverse proxy load balancer here and I have my application that does the author authentication right I have I have two services running here we talked about this many times gonna reference the load balancing videos if you're interested to know how this works and all that stuff and the client want to log in and when the Postgres database here or my sequel any database really I have a table a username and there is a password and there's a wrong password obviously not plain texture but think consider its be cryptid hash salted all that jazz right and I made a video about the password method of storing what is the most from Lee secures to the most secure go check it out right however we have the password stored here so and there is a user who says I want to login look what happened here right I'm gonna do it again make a request so we went to this server first and that server took that request which is post requests to login Edmund want to login and that's the password testing one two three and you might say well you're sending it as one clear text that's absolutely right because this puppy and this puppy are in a session which is called TLS and they are encrypted already right that's that's hunts the 443 okay so that's okay if you're sending that password plain takes everybody's doing that anyway right so but technically it's not a plaintext it is encrypted right so what's sitting that I get the information and I authenticate I know that the user is good and what I do i generates a big large random string and I store it in the same table or in any other table right I'm called session ID and what the session ID I'm gonna store as much metadata as possible user name the the role who is the admin is he a normal user when does this session expire when when was this user logged in last logged in every possible information you stored it there beautiful and now what we do is just return that session ID back to the user say hey user this is your session idea what does that mean that means since we are on a web architecture you are responsible sir to send me this session are you with every request because guess what HTTP is a stateless protocol that means you make a request right and we know who you are but did a second request you make we have no idea who you are it's a completely stateless because that record has this server could this server could be completely another server right we don't know who you are so you need to identify yourself with every request and that's what there is possible of the client so the client what it does says yeah I want to say hello this is a new arrest endpoint and here's my session ID how do I send it I don't care send it via cookies send it via off header send it as a post request send this at a get parameter I don't care you can use any method that is promising cause of each one was long as you send it to us we will take that session ID you the session ID by itself it doesn't have any info right how do I have the information I queried a table that session ID says ok who's this guy and I find that oh it said morning this is an admin and this is expired organ it's not as far so authenticated good so you don't have to send a username a password with every request just sending the session ID I know you all right there is an extra head to the database with every request you make well and then you send me back hey hi Adam on your good eye I know Asante cated you right that is pretty cool so what happened if I send another request you we go to another server and that's absolutely fine ok and that also works we send do hi and I wanted to explain that because there's a lot of session-based authentication is actually stateful well yeah yes and no well it is stateful as a system because I am storing the state which is the session ID in the database however my application is clearly stateless that's because I can destroy one server and my application will be still running right I would not the client will not be forced to login I didn't lose any information this guy can die this guy can die and they can resume if there is a new server they will absolutely resume as long as the database exists right so the database is the state the system is stateful but the application is stateless I want you to know there is a very very good important information to understand here right yes so it's not full yes it's still a stateful system but it's a stateless application right that's why scales here and you can make this as a primary kind of backup replicated the database so it can scale horizontally as well all right guys throw us the session based authentication right what's the problem of this well every quiz I make is actually taking extra latency to verify by this application to query the database and that's an extra hop and that's an extra it takes time right even if it's a rightist database even if it's a progress there is an extra latency people didn't like that right so some people came up with other search and says ok we're gonna catch on formation here right we're gonna query once and the session information will be is cached here on here but then you make your application stateful right and people didn't like that because ok how do I know that this information is up-to-date because you the moment you store this here you're out of sync right because you can the session could have been hijacked right someone hijacked the session and then yeah they you delete that session but this guy has a cache of it right you you get this inconsistent state and that's bad right there are a lot of ways to solve this but I'm not gonna this is out of our scope of this video we're gonna talk about it and it may be another little video right what people invented was Jade abilities a JSON web token stands for JSON web token it is a completely stateless system that means we want the application to be completely stares and the whole system to be stateless that means if I take that JWT and give it to a completely different service that has no access to my database it will be able to authenticate that guy all right how do we do that magic in corruption three parts it has a header and it has a data and a signature Humphrey I'm sure sure you're sick of listening to this song I'm not gonna go into details about this right so there's three parts of this where this is the header it tells you oh this is an algorithm encrypt the signature has been encrypted by this algorithm and there's the data the actual user name and role right put it in the token itself don't start in the database right but the moment you say this o husain if I put it in the data if it's okay self as a user I can make myself admin right and I'll just send it over and I'm an admin well no because that data will be verified by a signature that only the server can verify right so the signature can be either symmetrical or asymmetrical we're gonna go through that the symmetrical we talked about symmetric and asymmetric encryption I'm gonna reference the video here guys but in a nutshell you take a key you encrypt the data and you store it as a signature and the same key can also decrypt right so symmetrically require the same key to create and validate the token asymmetric private key right that's the asymmetric part where you can encrypt with a key but decrypt with another key right encrypt with a key and validate with another key the validation is public and there's like a pros and cons for using each of them right we're going to go through them people favor this more than this I'm going to about why it's how it looks like right and in my example Edmond Dantes as a name as the user and this is the role and this will expire at right and you as a server you build this token right you build this payload and then you say hey I'm gonna encrypt it with this algorithm which stands for H Mac sha-256 right so what do we use this algorithm is to encrypt this content and put it there so this is exactly the verify signature and to do that you need to provide a secret and the secret is the symmetric key that we talked about symmetric key because we used a symmetric key algorithm function here right if use a symmetric key like RSA then you provide a private key to create the token to verify you provide the public key and the public key can be sure we're going to talk about that in a minute right but but that's it the secret is known for the server that the client never knows the secret right so you store the secret here is the first kind of problem of this right secret keys right where do I put this key right all right take an example how does this work I'm gonna log in same exact thing guys right post plug-in it menthe testing on two three again this guy is encrypted remember this is a TLS probably right has to be TLS and then it goes here and said oh they didn't want this thing good let me query the database we still need to query it anyways right we're authentication we have to store them he was an impassible somewhere right okay I know I validated you you're good we we query the database now I know you right let me generate a token for you and here's what we do it we create a jason named Edmund roll Edmund and if you have attributes as much as possible put it there don't put sensitive information because this will be public this token will have all information put the things that you don't really care the user can see right so they can see but they cannot do much about it right so you put the information and then you take the symmetric key the secret right and that the secret which knows by the server and have to be ill known by older this server right you encrypt that with that a JWT library and that will generate a huge string that consists of three parts that we shown earlier and then you return that token to the user same exact scenario as the session you are responsible to send me this token with every request I don't care how do you send me this or this token authentication bearer some people do that because it's api's token cookies probably best way is to just do it as HTTP only cookie and strict and and same strict same site strict and if you want to be even more paranoid make it secure right and you send it I don't care how you send it just talking to me and here's the thing do you see what happened here that's it we didn't hit the database we only hit the server and the server immediately verified that this guy is admin and how here's how because it it has the same key the golden key which is the symmetric key it looked the same key encrypts and decrypts so I'm gonna take that token I have the information I didn't decrypt anything it's right there but I just want to verify that the token is right so I get a compare it against the signature part and if it's good that library tells me that's good looks good I'm gonna trust that and I'm gonna respond back hi Edmund I trust you I didn't even have to query a database to trust you and that is so powerful guys so powerful this is a truly stateless system I can take the same token and I send it to anybody who understand how to verify JWT and they will be able to verify themselves that's why both to is a big thing right I can verify with Google and they will give me a JD ut and then I take the jet ability and I absolutely can verify it right until it expires obviously so it's a completely stateless system people loved that didn't come it comes with a price comes with a price nothing is free right so what do we do that's a problem that key that same danke I have to share it with all my services right people who want to create secret JWT tokens and services that I want to verify I have to know the key but the moment you share that there is a problem right now okay well good another example here I'm going I hit that other server doesn't matter because that server has the exact game same code that verified and then it will respond back and here's where it breaks down guys alright guys so I might not trust the other service that I am I want that talking to be authenticated but that's another problem we're gonna talk about later but what's wrong with this right what is wrong with this particular token we're gonna talk about refresh tokens but what is wrong with this once it's stolen we can't do anything about it guys yeah if it doesn't have if it has like hundred days expiry enough has been stolen now we can coat and coat define what stolen mean I mean this cannot be stolen between this guy and this guy because this is encrypted right so the only loophole here is well I take it back if you are being man in the middle then that man in the middle attack er served you the certificate they can somehow hack capture that but that's extremely unlikely and if you know you don't know how to verify the certificate then you probably went to the situation but it's really unlikely let's take that they're more likely solution is that guy here in the browser or the client itself god attacked XSS cross-site scripting is a thing cross-site request forgery is another thing right they are going away at least a cross-site request forgery with cookie a introducing same size cookie they are going away but a cross-site scripting is a thing so once you stole it if someone stole that token they can present that talking to any service and they will absolutely be verified because guess what you cannot say hey this look is this token is no longer valid I'm gonna destroy it nope there's no database it's not in the session if the session was stolen you go to the database and you truncate your session you delete that session ID you're gone you're done that session is destroyed because there's a central location where the truth lie this is a stateless system if it's stolen tough luck you don't you cannot do anything about it everybody can just take that token and then verify themselves there are so many ways to solve this problem one way is refresh token another way is is to add some state to your state less jwz there cuz I'm gonna talk about that okay and so what do we do people said okay this access token thing which is this these tokens let's make them short left they have to be shortened because if in case they are stolen right what we're gonna do is they okay stolen stolen it's again the fact that they are we say stole them in a very light light way but it is really hard to steal tokens guys right because stealing tokens is not just something you do you cannot sniff in the middle this is encrypted right and the second thing is carrying out XSS attacks is extremely well-crafted it has to be well crafted to actually nail it so and yeah it's not that easy but if someone managed to do that we want to make this token as short as possible so they can only access I don't know 15 minutes right whatever but the moment we make it short left we gonna let say 15 minutes we're gonna tell the users hey users you're talking spoiled Logan again it's very bad user experience we can't force users to login every 15 minutes that's just dumb well banks do that and and that that might be a good idea but imagine a Facebook for Steve's you would log in every 15 minutes that's just dumb so we need a way to get a new JWT token every 15 minutes thus refresh tokens were born and what our refresh tokens there are exactly like sessions yes I said it this is exactly the same thing right what we brought it in it you know we added some state to it so refresh token is a JWT token that you store in a database right and it's still there is a valid there is value to this guy's right still there is value to this I don't got to talk about it so let's go through our exam exact scenario by whether a fresh token I'm worn on login my name is ed month this is my password all secure and jazz I hit that server and I often ticket myself because I had the database I have to check the password right and then what we do is we generate two things the we use the symmetric key right once we verify we'd use the symmetric key here we generate an access token which is short-lived maybe 10 minutes 15 minutes and then we generate a refresh token usually it's usually doesn't have expiry right but if you want to make it like make it one day right and then this is longer and we return both to the user right what here's what we do we return both of the users token use this to authenticate every request that you make use this in case this guy's expired to generate a new one okay we'll talk about that and here's what we did here we stored the token in the database itself but exactly like we did with the session yes I started in the same table but you could store it in another table and by doing that we kind of played like a session in a way right we're gonna talk about an example here let's see what was going on we're gonna and here's another thing this you can put in a cookie this you need to store it securely because this could be attacked by XSS and CSRF and they could be stole if they are stolen then you're absolutely screwed right because if this stone that's okay but this was stolen people can take it and just create their own tokens from it but we're gonna solve that problem as well right so let's see what will happen with the Refresh token I log in and obviously we don't have a base I am verified and then we take that we verified all that jazz good well the token has been expired what do we do all right so my post my token has just expired and I want a brand new talking but prior to expiry are I gonna make generate a new token so it's a client responsibility to get a brand new access token how do we do that you make a post request to an earth standpoint and you specify the refresh token I don't care how right probably securest ways to put it as a part of the authentication header here right or the body right no that's a cookie I wouldn't do it as a cookie to be honest but regardless once you do that look what happened geesh and we have the database we have to despite the refresh token being stateless I could have verified it with my symmetric key right but we don't want to do that we have to hit the database because guess what this could be stolen we don't know for sure we need to hit the database and verify that the token is still valid verify that the token has not been blacklisted maybe verify that the token has not been stolen and all this information right and this is now became a sensor system but it's still better still better than session authentication guys right it is still better because with every quiz I don't have to hit the database now I have to hit the database only with 15 after 15 minutes that's absolutely fine that's real really good right so now I'm gonna give you a new token and this will return basically a brand new access token the client is responsible to use this new token with every request I'm gonna show an example code example hopefully right guys so that's the Refresh token Wow all right very obviously as we said I'm gonna use the new token the access token to access and since this hi guy I have my symmetric key they can verify it and they know who I am the only trick here is the client is responsible to generate this new click talking so we put some work on the client right something we didn't have in the session ID right so it's a pros and cons game you playing here we're gonna talk about all of that stuff right really there is no favorite to be honest right you can't you can go with each one depends on your skis again alright sharing secrets guys how do I share secrets in a micro-services architecture with JWT we have this thing now that's called secrets right because yeah it's a stateless but guess what nothing spray I need your dang key to authenticate right but the moment you share that key right if this guy's like ok I'm verifying I'm whatever hey Leo to service hello to service be right want to authenticate this token you gotta give it that key and the moment you give it that key this guy could be evil and if this guy is evil they can generate their own token and they can make it unexpired right and they can just authenticate on your behalf that is absolutely bad right so absolutely very rare that people use symmetric key and microservices architecture especially in a zero trust architecture where nobody's trust anybody in this so what do we do meet asymmetric generality again guy what my encryption video if you want to learn more about symmetric vs. asymmetric but in a nutshell symmetric encryption is you incur to the same key and you did a crypt with the same key right what does that mean you encrypt with a key and you declare to the same key and it's absolutely powerful and fast a symmetric key you encrypt to the key and you decrypt with another key right or you encrypt with the key and you verify with another key all right so it's asymmetric and there's pros and cons we need both to make encryption work and security work we cannot handle just one Kerberos authentication actually just work on symmetric key in a very smart way right and I love that all right I really love that I'm gonna make a video about Kerberos yeah comment section below if you want to make you want to see the video about Kerberos it's really it's a old technology but is so badass all right asymmetric back back - that's helping so asymmetric JWT Oh jot right you the authentication service is only service that has the private key right and you can use it to generate these charts right but to authenticate you use the public key and you can give this away because this key is useless is you will only validate it will never be able to generate new keys so and you to do that you just used for example an RSA right you gotta be careful this because asymmetric key algorithms are slower than symmetric algorithms and if you have like a big JWT I don't know why would you have that asymmetric is absolutely slow with big data big data not big data big data big data big data you get it all right guys coding time let's jump to the coding and then we're gonna jump in and pros and cons of Jade ability how about we do that all right guys so initially I wanted to actually live code this one but in favor of time I noticed that the actual content is now 50 minutes so I don't want to spend more time just showing you how I code this so I have the source code I'm gonna explain it to you how I actually wrote it so how about we actually show the session based authentication code that I have and then show the JWT version and now we're gonna go through the code now exactly I did it how about we do that right I apologize for that maybe I gonna make another video to just live coding how I actually do that but it's gonna if I do this I'm gonna take me another maybe 40 minutes just - right the call from Scott so I apologize for that so all we have here is a session based authentication and I'm going and this is back backed up by the post cos database and hires the tables called sash oath and it's empty it has a user name/password role and session ID okay so we're gonna do here I'm gonna create a new user called test the password is also test and I'm gonna register him as a normal user and if I do that the moment I do that the password is you I'm using be corrupt to encrypt all that stuff in the password this is the test and this is now a user and there's no session because this user didn't logged in technically what we're gonna do is we got a submit a login so that was the register endpoint this was now the login endpoint if I do a login I'm gonna get back that this user is logged in successfully here's what happened here when I query the same thing I now have a session ID look at how long is this thing you can make it as long as as you want the longer the better the more secure and look what happened here and look what what happened here since as part of that login I set a session ID cookie right and this cookie is now is own HTTP only that means it will never be in access by document dot cookies so it cannot be accessed by JavaScript so it can only access by the session and only HTTP only so it will only be sent via HTTP and then Maya made it lacks right same sorry I meant I talked about same side cookie I'm gonna refer the video here guys but if you might can make a strict is even better but lacks is good so now the moment are you refresh the page the cookies will send the session ID right because that's what cookies does whatever a course they automatically do that magically for you look what happened the page has changed and now it's greeting me what is up hey you are a user and there's a button to log out and the page is blue because that's how a user affair if I'm gonna log in as admin I'm gonna show you it's become become red just just to show you that the their functionalities right so now I can automatically also logout and well logo to will do is literally no this thing out that's what it does and next time if i refresh i no longer know you so that's how fashion works very simple i'm gonna show you the code and the code would be available in the description below guys it's it's exactly how i did it right so that's that's the logic let's look at as an admin admin admin i'm gonna register a brand new admin user if i query now I have another entry and it's an admin how about we login login we get another session ID alright that's such an ID now we'll have the abdomens edgenuity right and if i refresh look at its now I am admin hey man what's up you are an admin that role is adamant so I use this like kind of an edge site includes right to to to render this HTML it's not really H citing flow but a similar very similar thing I render this the HTML on the server and ship it to the client alright so and then I thought I said man you can immediately log out right and it works the moment you log out that's it you're done so here is the source code guys and you can see with every request we have been validating the session by querying the database right and here's the source code it's it's really straightforward I have I'm using pool PG no not PG which we have talked about on the date and this channel before using a connection pooling to create a multiple connections and and every gets request to slash we need to value validate a session ID if the session ID is is there then go ahead and validate a session which is nothing but a query to the database where the session the idea of exists if it exists if it doesn't exist right now if exists return the information that we found from storing the user from the table itself if it's valid if it's not valid you're gonna go no then send back the login page if it's valid go ahead and read the user HTML and change these things so it reflects the user page that's exactly why I'm sending back the user and I'm just changing if it's admin do this light blue and color blue so it's it's readable the code is variables very simple but log in page is actually squaring the database and doing the password authentication that we talked about in another video and just sending it back this session all right all right let's do the JWT I'm gonna stop this go to launch and change this from session to JWT final and JWT both I'm using MJS because this is the new standard now and technically technically err codes you can the same code should run in the browser not not exactly because these are on the browser but you can light write a library like this that user import and have it execute on the browser as long as it makes sense you cannot query a database for a browser obviously all right refresh JWT base let's go ahead and just clear all the tokens and then say cookies that I have right boom let's just clear this guy because we don't run didn't need it so for GWT it's the same thing but we're gonna query another table called JWT oath and it doesn't have everything now and as username password role and token this is for that a fresh token right but what we're gonna do here is let's create a user called test register as admin oh I want to be a user never mind now this user is now an admin all right same thing so far I didn't use the ID ability but when I login here's what would they use here here's what where the server will give me it will give me a Jade ability this is the JWT give me actually two things gonna give me the Refresh token and the access token as well which is awesome so the access token has been set as it as a as a cookie right and there refresh token I stored it in the local storage so this is the this is the refresh token right so I stored the Refresh token in there and the local storage but the access token is in the cookie because it's more secure to have you don't have to send the Refresh token over I mean you can but it's kind of useless right so you stored and when your whether you need it your refresh in order to recreate a new token right so how about we actually refresh this thing the access token that I got is only is only 30 seconds I believe so if I log in my refresh you can see that I am logged in right but when I go to the console you can see that there is a process that is renewing my token every I believe every 30 seconds that's how I did it right because the token actually expires every 30 seconds you I have to renew it every time right otherwise I'm gonna get the page right so every time now I can I can keep using this token right but once it's expired right that cookies will be updated with my new token right jw2 again that's it I can I'll be logging forever that's the idea all right that is pretty cool huh now let's take an example of how you actually can log out right find a first year by the way you can see that the Refresh token is stored here right and I can I'm logged in as far as I know but every now and then I have a script in this page that actually generates a brand new access token so I can continue working right but how do I log out if I had log out what will happen here we nailed out this thing but since I still have an access token I can't do anything about it that will still be valid until the 32nd is up any second now and you will see that this page will will go away after a while there you go you know it is right so now the access token has been owned so that's kind of a bad thing compared to their session the session that immediately I looked out I logged out with access token the idea of logout doesn't exist guys because how do you unlock out logout is technically means take me out of this session make my token invalid and how do you make your token invalid there is no way the state isn't the token it's too late I have to generate a new talking boy I have to store the state that this token is logged out somewhere and the moment you do that it's a stateful right so the only solution you can do is this that I can think of to be honest log out you have to wait you kill the refresh token essentially all right that's how you log out all right let's go through the code the Jade ability oath very similar things I used accept the Jade JSON web token I'm using for Jade ability cookie parser I'm still using all that stuff I'm storing the secrets for both the access token and the Refresh token in the code bad idea never do this right use it store it as an environment variable or in a key management right you have to do you have a key management system if you want to use this stuff yes it comes with a price julia beauty is not free so yeah so you have these information and pull to query the database get requests give me this jason token a JWT token and the token is there I'm gonna validate the token and this is not equal to the database just give me the secret and I'm gonna verify Jade ability to verify give me a token give me a secret I'm verifying it if it's good I'm gonna return it if it's not good is there an eternal there is no query to the database that's the in line verification and it's pretty pretty fast right not much if you have a big tokens so careful that I don't guys let me know if there's there's a limit to Jade abilities token size I don't think there is but yeah if it's now that means send the logon page it's no longer valid that's what we saw right when keep refreshing and if it's valid go and read and change everything that same code we did with the session right make an admin role and all that jazz and send it back else if the user asked as the user has the logon this is for that refresh token slash token that means every time you post a request right I'm gonna validate the Refresh token using the Refresh secret right token and then if it's not valid I'm gonna return else I'm gonna query to see it's valid that refresh token is valid or not and it's not valid also fail if it's valid go ahead and just return a brand-new access tokens that's how weary sign it and I'm using the H Mac sha-256 to connect token sit the token in the cookie and I said it's in the back so that's that perfectly works and this is the login so all the code will be available for you guys here to play with that try obviously this is not the best practices to be honest right the postmarks is to use a vault or a key management to store all the cookies but the same idea holds the only bad thing about this is it's just the storing of the keys here right some people use environment variables but you have the same problem where do you store this environment variable where do you come and come up with the keys right you can put in the code a lot because if you store it this way you're pushing it to your git repo the code the secrets in the git repo that's bad you don't do this right so you mainly store it somewhere else that is not accessible to everybody alright guys so that's it really I'm gonna push the call for you guys and then here's the create sequel to create the tables if you want to spin up your own if you want a Postgres database it's really simple I check out my docker video because I spin up a docker Postgres it's just like in a few seconds you have a poster in running so you would clone this and npm install and all that jazz and we'll do all that stuff alright guys go back and talk about pros and cons how about we do that guys alright guys so that was the coding part how about we finish this video by talking about the pros and cons of JWT because something is perfect right that's what really depends on the use case so I started with the pros first guys the first thing a pros and absolutely a great advantage for Jade ability as it is stateless and it's a completely stateless system once you use it because you can throw this token in every service as long as the service has the secret key or the public key in that case it will be able to authenticate that without hitting a centralized database right at least for the just the access part of it okay so the access tokens they are beautiful for stateless yeah for refresh tokens there is a there is some sort of a centralization right because now you have to hit the auth service again to get at brand new access token but nevertheless right so it's great for api's because of this right now I can I can talk to end central authentication service right and I can build my own API and then everybody right if they want to authenticate they talk to me they get a token and they can you build their own application and they use my API as long as they provide that API right they're talking they can be logged in if you build another rest endpoint or another J graph QL and point you can use that a Jade ability to authenticate yourself without relying on a centralized database right and that that scales very very well for API so I people all the time use this right it's very very secure right because the security of it is because I have everything encrypted in the database in the in the token itself it's very very hard to actually break it unless you used a very weak secret or a very weak key symmetric key or private key that is right so it's secure right so people rely on them because of a secure it carries a lot of useful information that doesn't really require us to query the database to obtain them and that is so powerful and you can trust this information because it's secure back to the security right now right an accession based oath you have to only give the user the ID right that's you cannot give the user the actual username in a cookie you cannot toss that order you cannot give them a by the way this is your role and you you rely on them sending that to you know that's bad idea in a session base because they can just change that and make themself an admin right go to the cookies and the dev tools and change themselves to be an admin you never do that so you only have to have the session idea when you do that you have to store the information on the server and that's an extra hop extra latency that can slow you down if you have a lot of requests so it's very useful to have everything in the token itself so that's even the experience in the in the page right you can render pages and JavaScript on the client without having to rely on the server hey you have the GWT you have the username you have everything you don't have o user or server what's my serve what's my user name what's my add admin credentials no you cannot do you have you don't have to do that all the information is in the token and it is it is available for you it's not let's let's be very clear about this JW is itself is not encrypted it is signed right so the the text is a plain text is base64 but it's plain text you can actually read it the signature is encrypted right so you can actually read this without needing to decrypt it to be honest and as we said write can store information that drive user experience right just use that information and drive the user experience without relying on the server very powerful and we don't need a centralized database anymore to authenticate ourselves right this is a beautiful way just send stateless right take the apology it is somewhere else and you're good you're golden okay we ran out of pours how about we talk about cones the cones sharing secrets in a microservices architecture right and you guys when I made the YouTube stories you told me how much pain in the ass this is right if you have a building a microservices architecture and you rely on GWT that dang secret even if it's an environment variable you have to share it somewhere with all your service if you were raising symmetric-key that is right and that's a problem right because the moment you use that then sharing secret becomes really well do we would you put the key or do put in a database right or put in an author central authentication service right like vault you can use vault to do that and what's pretty good right storing all these secret management becomes all these secret management it's actually its own problem to solve and Walt from Hershey Corp I believe they solve this problem very elegantly so sharing secrets is a pain right sharing keys is a pain and the other problem is even if you use public private key which says okay I'm gonna share the public key but where do you put this public key right and how do you know that this public key is still valid let's see the private key of the token of their service has been leaked somehow the heartbleed I don't know and then yeah and then people started generating their own token and then that pup that pairing public key is no longer valid and if it's no longer valid old request should be stopped right all tokens are just done how do you do that how do you deprecated a key well you can say okay let's just delete that can use this public key but what do we do with that old tokens that they are still valid do you trust them or do you say no guys we don't trust anything before that date all these public all these jars they're being created with this Alt key you know we don't want it anymore then so key management is obtained where do you to put this public key it's so it's kind of back to you still have this latency with with key management right because you're gonna either put it in a smarter service authentication micro-service that rely on key management or you put an own vault or eeper is somewhere you have that extra latency to verify the key so it's kind of back to the same problem with the session which is that extra hop right you cannot escape that yeah it's it's attractive but that problem still exists right and it's painful I'm gonna refer the video guys for one doctors named Philip I forgot his last name buddy he's very very very good very good at presentation talking about the bad practices with durability and what people bad things are dead with that so a key management is a thing and people's trying to still solve this problem it's very tricky to consume correctly I didn't say implement but consume the client is now responsible to deal with this access token and and it needs to know where exactly centered whether it's whether an authentication as a bearer property or whether as a cookie or whether as a post request and when it knows that well it needs to know that oh this token is about to expire and let me generate a new refresh token and it needs to build this token in itself which is annoying we never had to do this with the session IDs before right if the session is exploring this expire this session does not expire restoring tough luck the admin goes to the database a also this session is done I guess there's deleted and the next request will just invalidate that session so it's very simply elegantly designed previously right yeah there is this extra hop which we can solve with state a little bit of statefulness in this in the server but yeah still you're adding some extra complexity to the clients right nevertheless it is complex and tricky I'm gonna say gonna fix a complex it's tricky right again guys if I'm saying anything that is doesn't make sense let me know because I don't know everything right I know what I read and research and everyday from you guys learning input watching other videos and and implemented it myself that's what I find it's just completely my opinion right prove me wrong let's have a discussion right and then let's just say what's your method best method of authentication really there is no there is no best or favorite method it's just really depends on the use case to be honest storage of refresh tokens now we have the same problem right the token is a precious access talk is not that brushes you can put in the cookie right because it's just short-lived but the fresh talking is longer than this stolen it's a problem so where do you where do you put it you put in the local storage JavaScript like we did that's susceptible to XSS attacks cross-site scripting what do you do you encrypt it what do you encrypt it with a key where do you solve that key it's the same problem it's it's a very hard problem guys people are still figuring this stuff out it's a very hard problem you can solve store it anywhere you want I would prefer as an index DB because index DB has a little bit enjoy and it has a little bit of more security than local storage to be honest but index TV's API is bad as token revocation and control same thing token this guy whoever whomever we assured this access token or refresh token turns out to be shady and shady people deserve no more access how do we revoke that tough luck you cannot revolt a Jade ability durability is a stateless there is no where do you store the state that oh this is no longer valid where do you store this database somewhere right you can say okay I'm not gonna storm database on guest on an author authentication service yes then this authentication service has to store it in a database obviously guys right so yeah take token revocation and control like controlling who access has access to what old this token is it's still valid but this guy cannot access this resource anymore this cannot access the pictures because I don't know he's doing something Shady we don't want him to access the pictures but they can still read the comments I don't know something like that so how do you revoke control right how do you do this stuff back to the centralization with session IDs you can still do that very easily because it's a centralized design right with this this decentralization with I'm not sure that decentralization is the right what to be honest but the statelessness that means the state is in the token all the time we have no way to change the state in the token right it's there so it's a very tricky problem to solve people are still doing it right you can still have asynchronous calls on the server that periodically check the state of the token I would go that method to be honest even with a session ID right you don't you don't want to hit this database every time with each session you store something locally and you pull it every another 15 minutes or so and six check the latest state so you're you're fast when a request comes in and you don't and basically take that and there is the unsecure implementation of libraries that I took this point actually from from Phillip Bev Phillip Dirac I'm gonna put his twitter below right so in his presentation he talked about some of the insecure implementation of libraries right so it's like what happened if you don't you put none as the algorithm in a JWT right that's a perfectly valid token and people did that right and if you did none that means it's not really encrypted that means the signature is empty that means I can just make up my own JWT and I pretend to be an admin I claim to be an admin I didn't know I didn't use that word a lot but that's what database he does it claims right I'm claiming to be an admin and you're gonna believe me because your library support none has an algorithm because there's no encryption there's no signature so yeah ow I blew me away when I read that's like what some library did that and it was there until 2015 when somebody actually discovered us like what yeah so do you trust the libraries baby right what do you think Jade ability or know German ability what love do we give to what right session IDs good old session ID because your whole old school 90s kid or your hip your 2020 kind of a guy or gal that likes jail abilities right I'd use that ability to be honest it's a beautiful design right and to be honest I'm not gonna use refresh tokens I think it's a they I don't think they are I would just use J access tokens right and here's what I'm gonna do I'm gonna use access tokens right only access tokens and what I'm gonna do on the back end I'm gonna store the access token I'm gonna make access token and limited there's no time limit to it and I'm gonna store the token in the database and every 10 minutes asynchronously on my server I'm gonna pull the database as a is this token valid it's just talking about it still talking about so that if the token was stolen I can just I know that stolen because maybe I got requests from an another IP address that I'm not supposed to or has been reported to be stolen I'll just go to the database and delete the entry and then for the next 15 minutes they the attacker will have access to that token but after that they will no longer have access because I'm gonna delete that the server will discover oh that's bad so I would do it this way to be honest that but that's just me now I think the idea of refresh token is is really unnecessary to be honest I just find it really it's just wow why do you put the blame on day on the client to do all the work generating you talk and everything it's just it's an extra I don't know extra complexity I know off to does it and there's probably a good reason for it I still don't understand it because there's better ways of solving things right but that's just me might be wrong all right guys let's search for me today I'm gonna see you in the next one you guys stay awesome
Info
Channel: Hussein Nasser
Views: 20,036
Rating: undefined out of 5
Keywords: jwt, json web token, jwt refresh token, jwt vs session, json web token nodejs, jwt nodejs, jwt docker, jwt deno, jwt access token, jwt refresh token new, jwt local storage, jwt store javascript, jwt security, jwt vs session based, jwt php, json web token authentication header, jwt vs session auth
Id: T0k-3Ze4NLo
Channel Id: undefined
Length: 57min 1sec (3421 seconds)
Published: Fri Apr 24 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.