JWT Authentication with Access Tokens & Refresh Tokens - Node.js

preview_player
Показать описание

0:00 Introduction
2:11 Demo
4:02 Code walkthrough
12:10 Granting an access token
21:01 Using the access token
24:54 Revoking an access token
26:40 Granting a refresh token
26:59 Outro

In this video, we take a deep dive into JSON Web Tokens, how to use them as access tokens, the problems with a completely stateless application, and how to solve those problems with refresh tokens.

JSON Web Tokens are made up of 3 base64 encoded objects concatenated into a single string. The first string is the header, the second is the payload and the third is an encrypted signature.

The header portion of the token contains metadata or data about the token such as the signing algorithm and the token type.

The payload is a JSON object that you want to store in the token. There are reserved keys such as iss and exp that you can't use. You should never store sensitive information in the payload, such as passwords.

The signature is generated by encrypting the header and payload base64 strings with your private key.

If the header or payload data change, the secret will no longer match the header and payload strings, making the JWT invalid.

Access tokens are granted to users when they have proven to be who they claim to be, usually by logging in. The bearer of these tokens can make subsequent requests and provide the token as proof that they are who they claim to be.

Using JWTs as access tokens allows your system to be stateless, meaning the system does not need to have access to a stateful data source, such as a database, to verify and extract the data from the token. This is great for scaling applications but introduces a new problem.

We need to be able to force a single user to log out and make sure the user does not need to log in every few minutes.

The solution to these problems is refresh tokens.

Refresh tokens allow the system to provide short-lived access tokens. When a request is made that includes a valid access token that has not expired, access is granted for that request.

However, if the access token has expired but the request includes a valid refresh token, we can do a single trip to the database to make sure the user’s session is still valid and if it is, provide them with a new access token.

In this video, we are going to look into the anatomy of JSON web tokens, granting access tokens, and how to use fresh tokens.

By watching the entire video you will understand the concepts that power JSON Web tokens and how to build your own secure authentication system using JSON web tokens.

📚 Concepts & technologies covered
- JWT
- Access tokens
- Refresh tokens
- Cookies

🌎 Follow me here:
Комментарии
Автор

Hello, In my projects I get the token and store it in 'localStorage'.
In the request I use the Authorization Bearer + token header.
And I use axios interceptors response to make a post to a `refresh_token` route and get an `refresh_token`.

*My doubts:*
What's the advantage of using it like you did, compared to my example?
Is it possible to use the Authorization Bearer header, following your example?
How can I handle the token if I want to use it as rest API?

wagnerfillio
Автор

Thanks great video. Liked the code walk through in the start made very nice to follow.

the_full_stack_junkie
Автор

Most underrated Youtube channel of All TIME

shihou
Автор

My wep-page crashes when the jwt token expires and I have to manually delete my expired token from the localStorage for the page to work again, why is that happening and how i can solve it ? Note: I’m not using a refresh token .

TheGlitchOfTheGame
Автор

Just 10 min in, already loving it very descriptive really good thank you ❤

chaitanyakulkarni
Автор

Thanks for making this video. Being able to code along really helped me to properly understand the logic behind JWT auth at last 👍🏾

stevereid
Автор

Thank you. You make me to understand in simple way.

todaystox
Автор

Hi Tom. Wow, awesome tutorial. That is what I was looking for. I see all your Videos. Love from Our side and Thanks.

qodecamp
Автор

Question.
Why does the "accessToken" cookie have an expiration date of 5 minutes but the token itself has 5 seconds?
Why the different value? Why not same 5minutes/5minutes or 5seconds/5seconds?

RockBell
Автор

Hi Tom!, thank you for making this amazing course!
I just have a question.
I make a request to the login API and I receive the refresh token that is in the cookie and the access token that is in the response body. Now how should I handle the access token on the client side(next js)? If I store this in a global state like context API, then I don't have access to that state in the getServerSideProps function, and I can't set it in the request.header.authorization because getServerSideProps run on the server side and the state is on the client side!
what is the right flow for this kind of case?

Mike-xrfk
Автор

If I were to have a table User with a session column to set it either true or false depending on whether the user has logged in or logged out, would that mean you can only log in in one device?

antony-xldd
Автор

Hi Tom congrats for the great video. It seems like you took in consideration the feedback from previous videos :) You improved a lot! Thank you! You just won my subscription. One question pls: If the api is used my a mobile app, would the cookies work or that's something browser related?

nuno
Автор

Am I missing something? After 5 minutes, when the accessToken cookie has expired, it isn't sent along with a Get Session request. Making it hit line 8 in deserializeUser, run next() without a req.user and fail requireUser.

It seems like this system relies on that accessToken cookie being sent even after it has expired.. Which won't ever happen, right?

Should the accessToken COOKIE expire in 1 year but the TOKEN itself expire in 5 mins? I'm new to this auth stuff, sorry if I'm misunderstanding something.

CaseyFronk
Автор

Thanks for the video. Can you make a frontend refresh token flow with react?

Shoutiez
Автор

thanks for the video. it is very helpful for me

beratdinckan
Автор

so the middleware execution to verify a user is as follow, DeserialiseUser => requireUser => endpoint. In deserialiseUser we are checking to see if request.cookies has a accessToken if not we are just calling next(), which will than execute requireUser. since we have not added a request.user in the request object because we did not find a accessToken attached, requireUser will throw error.

but what if user just adds a empty object to the post request.user from the front end without the accessToken in the cookies.
this means that in DeserialiseUser, it will call next because no accessToken was found in the cookies, but requireUser will not throw error this time, because request.user already exists as it was already added from the front end. is this a flaw or am I missing something?

naveedalirehmani
Автор

Hello sir, I really appreciate this video, its really cool it solved my problem

abrahamcovenant
Автор

Why set the cookie with authToken to 5 mins? The function deserializeUser does not check refresh token when there is no access token... I think that the cookie should be set to the same value for cookies as the access token validity is determined by the API server according to the token payload and not the cookie....

radekhladik
Автор

I love how in depth this video is. Thank you for uploading it. I wonder though is the juice worth the squeeze when you could just use express-session without jwt.

eyeiozm
Автор

I'm confused though; isn't the entire point of using JWTs is so that the server doesn't have to store sessions? Why even bother with a refresh JWT / access JWT, if we're essentially just building another session-based authorization system anyway?

PaulFidika