No video

Refreshing Tokens With Axios Interceptors

  Рет қаралды 88,869

Dennis Ivy

Dennis Ivy

Күн бұрын

Implementing JWT access and refresh token authentication with Django & React using axios interceptor method. This video is a continuation of my last project that can be found here: • Authentication & Refre...
Check out my Python Django course: dub.sh/fkXTrSo
Starter Code: github.com/div...
Final Source code: github.com/div...
Axios Documentation: axios-http.com/
Timestamps:
00:00 - Intro
00:53 - What are Interceptors
2:42 - Resources
3:30 - Code Recap
10:00 - Create Axios Instance
16:05 - Using Axios Instance
18:05 - Adding Interceptor
22:34 - Checking Token Expiration
26:50 - Getting New Token
30:45- Custom useAxios() Hook

Пікірлер: 76
@DennisIvy
@DennisIvy 25 күн бұрын
Don't forget to check out my Complete Django course: dub.sh/fkXTrSo
@supersecretninjame
@supersecretninjame Жыл бұрын
i think the reason that people check in in the response rather than pre-request is that it is a more general approach that works on a wider range of back-end applications where you are not 100% sure of how the back-end is set up and how it validates the tokens. For example if there is something other than time that makes the token invalid, you renew the token as a standard procedure upon request fail regardless of why that is. However, if you have full control over the back-end and know all possible outcomes (aka you know that you need to check the exp time) I think intercepting before the request makes more much more sense.
@matthewdillingham4941
@matthewdillingham4941 2 жыл бұрын
It's pretty neat seeing this done. I actually used this configuration on a project a few months ago. Was very surprised back then that I didn't see people validating it first.
@zayminmaw
@zayminmaw 2 жыл бұрын
Finally.... good explanation and with an example. Nothing can't get better than this. Thanks for the amazing content.
@teodorfredriksson
@teodorfredriksson 4 ай бұрын
Rarerly comment but this was absolutely amazingly explained. Well done and thank you for relieving me from my headache :p Loved the hook integration.
@andersonsimeon4172
@andersonsimeon4172 Жыл бұрын
This is legit the best video I found on this topic. Also, we use the same vscode theme.. lol
@AnthOo0ny
@AnthOo0ny 6 ай бұрын
what theme isit?
@andersonsimeon4172
@andersonsimeon4172 6 ай бұрын
@@AnthOo0ny It's called theme
@AnthOo0ny
@AnthOo0ny 6 ай бұрын
@@andersonsimeon4172 Thanks man
@stammeringprogrammer7535
@stammeringprogrammer7535 2 жыл бұрын
That's my boy, I started following u since last year. You're awesome
@tech3425
@tech3425 Жыл бұрын
Nice explanation man. Your side tangents really helped us understand the entire context.
@gregruiz921
@gregruiz921 2 жыл бұрын
This is very high quality content Dennis... thank you for your time and effort put into this production.
@Ganapamanoj
@Ganapamanoj Ай бұрын
We can separate the interceptor creation code from the useAxios hook definition to avoid creating a new axios instance whenever we call useAxios() from components.
@sarbottamchatterjee5814
@sarbottamchatterjee5814 Жыл бұрын
Forgive me if I am wrong, but shouldnot we check the expiry of the refresh token too before requesting a new access and refresh token? Just in case the user hasn't logged in for more than 90 days, so we simply logout the user.
@joaoarthurbandeira
@joaoarthurbandeira Жыл бұрын
Hey Dennis! Excellent tutorial, as always! Can you also show us how to do registration and also how a logged in authenticated user can do post requests to create/update notes? Cheers, bro!
@user-ke4yx6uw1r
@user-ke4yx6uw1r 2 жыл бұрын
I wish I could give 10000000 likes. This is exactly what I needed
@thebetoxpro
@thebetoxpro Жыл бұрын
Amazingg!!! Thanks for this, i have been trying to learn how to manage the auth flow and now i know how. Thank u soo muchh. Saludos desde Mexico
@tobidegnon4409
@tobidegnon4409 2 жыл бұрын
The only reason I see for the first option is that it's probably less request expensive in the case of an app with a huge amount of network requests, with your method you do a check on each request, but with the first option you only receive a bad request now and then when the token is expired
@juhandvan
@juhandvan 2 жыл бұрын
Next time I hope you will guide how to handle possible errors using axios. Many thanks !!!
@zamanEhsani
@zamanEhsani 2 ай бұрын
Dennis, It was very nice. I have to jump back and refresh my brain on this. A question; What is the best way, or what is the best place to store and save access tokens and refresh on the client ? localstorage, or session or cookies ?
@RaZoRxan
@RaZoRxan Жыл бұрын
this would create a race condition when multiple requests starts in parallel. Example: Request A has expired token -> refresh token POST request starts to renew it -> While the refresh request is still going Request B enters the chat -> has expired token -> starts a new Refresh Token Request. This creates a race condition. A lock/queue mechanism MUST be implemented to call this a real solution. I'm sorry but this tutorial is actually misleading.
@rockyGonnaHurtYou
@rockyGonnaHurtYou 2 ай бұрын
Thanks bro ❤️💯
@i_am_a_robot5625
@i_am_a_robot5625 Ай бұрын
save the status of the current request in a state , use eject method , call refresh token endpoint , set state of new accesstoken , retry the saved request .
@kleidilamka4518
@kleidilamka4518 2 жыл бұрын
Great tutorial. Thank you for the quality content!
@januwa9430
@januwa9430 2 жыл бұрын
This has some problems. When the token expires, when multiple requests are sent at the same time, the `token/refresh/` interface will be called multiple times.
@fachrurrazi95
@fachrurrazi95 2 жыл бұрын
Just cancel it when multiple request at the same time. Maybe can fix that problem
@ThuyNguyen-wn9hc
@ThuyNguyen-wn9hc 2 жыл бұрын
Did you solve this problem? If yes, then could you post the answer? I am in a very similar situation too.
@fachrurrazi95
@fachrurrazi95 2 жыл бұрын
@@ThuyNguyen-wn9hc just cancel your request if more than one
@ThuyNguyen-wn9hc
@ThuyNguyen-wn9hc 2 жыл бұрын
@@fachrurrazi95 Thanks for your answer, could you please share your additional code based on the tutorial code to handle that logic? I've tried to implement it in different ways but it still doesn't work. I'm a very newbie. Looking forward to your reply.
@nileses9300
@nileses9300 2 жыл бұрын
is anyone solve multiple refresh token problem?
@bismarcknyaboemomanyi6125
@bismarcknyaboemomanyi6125 2 жыл бұрын
thanks for the course dennis
@haritpatel5001
@haritpatel5001 Жыл бұрын
Amazing video, learned a lot...
@zahrareyhanian2859
@zahrareyhanian2859 2 жыл бұрын
Thak you for this awesome video.
@aj14775
@aj14775 Жыл бұрын
the api should really be in the dependency array of the useeffect, but that would then cause an infinite re-render loop
@serageibraheem2386
@serageibraheem2386 2 жыл бұрын
Great job buddy.. thanks
@abubakirmahkamov
@abubakirmahkamov 5 ай бұрын
pretty explanation.
@kiprutobarno
@kiprutobarno Жыл бұрын
Great stuff!
@0xinconnu
@0xinconnu 3 ай бұрын
26:50 • Use refresh token
@gowthamtharan6818
@gowthamtharan6818 2 жыл бұрын
I think for this use case the custom redux middleware will help when multiple requests are sent at the same time
@TheGraphStyle
@TheGraphStyle 2 жыл бұрын
Hello everyone, first of all I'm sorry for my bad English I'm tall and I've worked with the translator xd Well, I think that in react in the updateToken function in the first conditional after creating data (yes, the one with status === 200) the resfresh token should be added in data, at least if I don't add it, the resfresh doesn't work since it needs to. Greetings and good night to all coders ;)
@alialavizadeh2775
@alialavizadeh2775 2 жыл бұрын
I wish you do one another video using redux it would amazing like this one
@hodasj
@hodasj 2 жыл бұрын
what if the refresh token is expired? you haven't handled it right?
@Salmanfaris-pg2jw
@Salmanfaris-pg2jw 2 жыл бұрын
as access token expires we will create a new one using the middleware right? but if access token expires how we are going to use the refresh token as we will not have the authorization
@kathir1188
@kathir1188 7 ай бұрын
i have one doubt for react native "jwt-decode" not working. Can anyone help in that issue?
@albythekkedan
@albythekkedan 6 ай бұрын
Becasue it is jwtDecode now
@StickMan1316
@StickMan1316 2 жыл бұрын
I'm having an issue when I first login and my Authtoken doesn't appear. because of this I would have to refresh the page then it's there along with other backEnd data. How do I fix this? I've google this issue and couldn't find any solution.
@baetraki7268
@baetraki7268 2 жыл бұрын
can you make this with redux please
@lifeofboringintrovert1350
@lifeofboringintrovert1350 2 жыл бұрын
Thank you
@paulobruno1267
@paulobruno1267 Жыл бұрын
Thank youuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
@Salmanfaris-pg2jw
@Salmanfaris-pg2jw 2 жыл бұрын
how we are getting data from authcontext to useaxios as it is out of the wrapper
@ritankarbhattacharjee7661
@ritankarbhattacharjee7661 2 жыл бұрын
For some reason I am not getting the authToken on the first call. It still remains null. What is the reason for this as in the video there is no error.
@safaemre9693
@safaemre9693 2 жыл бұрын
You cannot know your clients time is set correctly. Just because of this i prefer to use response interceptors.
@amosndonga.netcnextjsitsup5982
@amosndonga.netcnextjsitsup5982 2 жыл бұрын
Good stuff, man, can you do one on password reset plz
@abhaybabbar395
@abhaybabbar395 2 жыл бұрын
hey, what if we store the token in HTTP Only Cookie, as it is safe from attack, and we cannot get its value, then following the Intro approach will be great I believe, right?
@DennisIvy
@DennisIvy 2 жыл бұрын
That would only work if you were doing client side rendering, and still, does not fully secure your app. Also, now days, I don’t think it really matters anymore. If you are vulnerable to any xss attacks then it really doesn’t matter where you store your tokens. You’ll need to take other measures to protect your app. A locked door won’t help if the intruder can get in through the window. Check this talk about with Ben Awad: kzfaq.info/get/bejne/rNdoaZSJ1MCtaZ8.html
@dilanmadusanka7059
@dilanmadusanka7059 2 жыл бұрын
what about the way your useAxios hook being called inside multiple components ( lets say four component mounted with useAxios hook when browser refresh ) . it will significantly grow interceptor listener handler and each time when make http call one call made four refresh token request. how can you handle this use case in that way
@exequielarroyo
@exequielarroyo 2 жыл бұрын
add a useEffect and use the return function to eject the axiosInterceptor useEffect(() => { const requestIntercept = axiosPrivate.interceptors.request.use(async (req) => { const isExpired = dayjs.unix(jwt_decode(auth.access).exp).diff(dayjs()) < 1; if (!isExpired) return req; const res = await axios.post( `${process.env.REACT_APP_SEARCHERSE_URL}/api/token/refresh/`, { refresh: JSON.parse(localStorage.getItem("token")).refresh, } ); console.log("interceptors.request.use"); localStorage.setItem("token", JSON.stringify(res.data)); setAuth(res.data); req.headers.Authorization = `Bearer ${res.data.access}`; return req; }); return () => { axiosPrivate.interceptors.request.eject(requestIntercept); }; }, []);
@jonirusieshvili6623
@jonirusieshvili6623 Жыл бұрын
hi guys 🙏🙏 i have this kind of problem : first of all I've set the access token on the http only cookie so I can't use jwt-decode to checkout expire date on axios request interseptors. After that I have to use response interceptor and problem comes here exactly. I'm sending 2 http request same time and when the jwt is expired it's expired for both of them same time , so refresher function from response interceptor runs two times, first one is succeed with existing refreshToken, but after the first one is succeed second one tries to refresh token with old refreshtoken which one causes the error. can you tell me how to solve this problem ?
@jose.oviedo
@jose.oviedo Жыл бұрын
I have the same problem, could you solve it?
@NoName-pb5tl
@NoName-pb5tl 2 жыл бұрын
How can I prevent several refresh token requests?
@exequielarroyo
@exequielarroyo 2 жыл бұрын
add a useEffect and use the return function to eject the axiosInterceptor useEffect(() => { const requestIntercept = axiosPrivate.interceptors.request.use(async (req) => { const isExpired = dayjs.unix(jwt_decode(auth.access).exp).diff(dayjs()) < 1; if (!isExpired) return req; const res = await axios.post( `${process.env.REACT_APP_SEARCHERSE_URL}/api/token/refresh/`, { refresh: JSON.parse(localStorage.getItem("token")).refresh, } ); console.log("interceptors.request.use"); localStorage.setItem("token", JSON.stringify(res.data)); setAuth(res.data); req.headers.Authorization = `Bearer ${res.data.access}`; return req; }); return () => { axiosPrivate.interceptors.request.eject(requestIntercept); }; }, []);
@Salmanfaris-pg2jw
@Salmanfaris-pg2jw 2 жыл бұрын
why this method is not good : 1. if you switch device you will have to login each time. 2. there is no use with blacklisting refresh token ,there is no extra security or anything like that . there will be a ton of blacklisted refresh token in your data base.
@mohamedyoussef8835
@mohamedyoussef8835 2 жыл бұрын
Awesome +++++++++++++++++++++++++++++
@blackpetergriffin179
@blackpetergriffin179 2 жыл бұрын
Man please Do Django authentication with email and otp verifcation
@devdive24
@devdive24 2 жыл бұрын
I need your desktop background image
@mysteriousbillionaire7349
@mysteriousbillionaire7349 Жыл бұрын
Anything on social login please?
@user-ke4yx6uw1r
@user-ke4yx6uw1r 2 жыл бұрын
19:39
@GetBackTrolling
@GetBackTrolling 2 жыл бұрын
localstorage? really..
@youtubegarbage4u
@youtubegarbage4u 2 жыл бұрын
40 minutes for this tutorial?!? common man
Refreshing Tokens With Fetch | Custom Interceptor
39:51
Dennis Ivy
Рет қаралды 17 М.
A teacher captured the cutest moment at the nursery #shorts
00:33
Fabiosa Stories
Рет қаралды 61 МЛН
A little girl was shy at her first ballet lesson #shorts
00:35
Fabiosa Animated
Рет қаралды 21 МЛН
Authentication & Refreshing Tokens Implementation
2:09:53
Dennis Ivy
Рет қаралды 231 М.
We're on the brink of another world browser war
4:29
Fireship
Рет қаралды 993 М.
Clean Architecture vs Domain-Driven Design (DDD) - Understand the Difference
11:26
Walking Away From JavaScript
1:06:44
ThePrimeTime
Рет қаралды 153 М.
Session Vs JWT: The Differences You May Not Know!
7:00
ByteByteGo
Рет қаралды 104 М.
Django 5.1 will be more secure by default
6:53
Dennis Ivy
Рет қаралды 7 М.
Pydantic Tutorial • Solving Python's Biggest Problem
11:07
pixegami
Рет қаралды 261 М.