Refreshing Tokens With Axios Interceptors

  Рет қаралды 91,828

Dennis Ivy

Dennis Ivy

Күн бұрын

Пікірлер: 80
@DennisIvy
@DennisIvy 3 ай бұрын
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 3 жыл бұрын
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 3 жыл бұрын
Finally.... good explanation and with an example. Nothing can't get better than this. Thanks for the amazing content.
@andersonsimeon4172
@andersonsimeon4172 Жыл бұрын
This is legit the best video I found on this topic. Also, we use the same vscode theme.. lol
@AnthOo0ny
@AnthOo0ny 8 ай бұрын
what theme isit?
@andersonsimeon4172
@andersonsimeon4172 8 ай бұрын
@@AnthOo0ny It's called theme
@AnthOo0ny
@AnthOo0ny 8 ай бұрын
@@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.
@teodorfredriksson
@teodorfredriksson 7 ай бұрын
Rarerly comment but this was absolutely amazingly explained. Well done and thank you for relieving me from my headache :p Loved the hook integration.
@juhandvan
@juhandvan 3 жыл бұрын
Next time I hope you will guide how to handle possible errors using axios. Many thanks !!!
@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!
@Ganapamanoj
@Ganapamanoj 3 ай бұрын
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.
@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 4 ай бұрын
Thanks bro ❤️💯
@i_am_a_robot5625
@i_am_a_robot5625 4 ай бұрын
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 .
@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 3 жыл бұрын
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
@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.
@gunderalex
@gunderalex Ай бұрын
i think it should be done on the backend side because refresh token are in httpOnly cookies which are not accessible to frontend. As i understood refreshing access token is supposed to be implement by backend API and in that way server will send a new access token (if the refresh token is still ok) or throw an error and require a login
@স্বচ্ছনিরবতা
@স্বচ্ছনিরবতা 3 жыл бұрын
I wish I could give 10000000 likes. This is exactly what I needed
@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?
@kleidilamka4518
@kleidilamka4518 2 жыл бұрын
Great tutorial. Thank you for the quality content!
@zamanEhsani
@zamanEhsani 4 ай бұрын
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 ?
@Iam_megamind
@Iam_megamind Ай бұрын
Best is to save it in application memory like redux or zustand store.
@aj14775
@aj14775 Жыл бұрын
the api should really be in the dependency array of the useeffect, but that would then cause an infinite re-render loop
@gregruiz921
@gregruiz921 2 жыл бұрын
This is very high quality content Dennis... thank you for your time and effort put into this production.
@PratikKumarVishwakarma-sb4ue
@PratikKumarVishwakarma-sb4ue 13 күн бұрын
If my refresh token gets expired then I have clear path in redux also, how to call dispatch in axios instance file
@hodasj
@hodasj 2 жыл бұрын
what if the refresh token is expired? you haven't handled it right?
@bismarcknyaboemomanyi6125
@bismarcknyaboemomanyi6125 3 жыл бұрын
thanks for the course dennis
@haritpatel5001
@haritpatel5001 Жыл бұрын
Amazing video, learned a lot...
@kiprutobarno
@kiprutobarno Жыл бұрын
Great stuff!
@zahrareyhanian2859
@zahrareyhanian2859 2 жыл бұрын
Thak you for this awesome video.
@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
@serageibraheem2386
@serageibraheem2386 3 жыл бұрын
Great job buddy.. thanks
@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.
@gowthamtharan6818
@gowthamtharan6818 2 жыл бұрын
I think for this use case the custom redux middleware will help when multiple requests are sent at the same time
@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.
@Salmanfaris-pg2jw
@Salmanfaris-pg2jw 2 жыл бұрын
how we are getting data from authcontext to useaxios as it is out of the wrapper
@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 ;)
@abubakirmahkamov
@abubakirmahkamov 8 ай бұрын
pretty explanation.
@kathir1188
@kathir1188 9 ай бұрын
i have one doubt for react native "jwt-decode" not working. Can anyone help in that issue?
@albythekkedan
@albythekkedan 8 ай бұрын
Becasue it is jwtDecode now
@abhaybabbar395
@abhaybabbar395 3 жыл бұрын
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 3 жыл бұрын
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: kzbin.info/www/bejne/rKKbZ2SOpL98b80
@baetraki7268
@baetraki7268 2 жыл бұрын
can you make this with redux please
@alialavizadeh2775
@alialavizadeh2775 3 жыл бұрын
I wish you do one another video using redux it would amazing like this one
@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); }; }, []);
@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); }; }, []);
@amaangigani9372
@amaangigani9372 Ай бұрын
Doesn't work.that well with use dispatch for reducer actions
@safaemre9693
@safaemre9693 2 жыл бұрын
You cannot know your clients time is set correctly. Just because of this i prefer to use response interceptors.
@jonirusieshvili6623
@jonirusieshvili6623 2 жыл бұрын
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?
@mysteriousbillionaire7349
@mysteriousbillionaire7349 2 жыл бұрын
Anything on social login please?
@paulobruno1267
@paulobruno1267 Жыл бұрын
Thank youuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
@lifeofboringintrovert1350
@lifeofboringintrovert1350 3 жыл бұрын
Thank you
@0xinconnu
@0xinconnu 5 ай бұрын
26:50 • Use refresh token
@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.
@devdive24
@devdive24 2 жыл бұрын
I need your desktop background image
@amosndonga.netcnextjsitsup5982
@amosndonga.netcnextjsitsup5982 3 жыл бұрын
Good stuff, man, can you do one on password reset plz
@blackpetergriffin179
@blackpetergriffin179 3 жыл бұрын
Man please Do Django authentication with email and otp verifcation
@GetBackTrolling
@GetBackTrolling 2 жыл бұрын
localstorage? really..
@mohamedyoussef8835
@mohamedyoussef8835 2 жыл бұрын
Awesome +++++++++++++++++++++++++++++
@স্বচ্ছনিরবতা
@স্বচ্ছনিরবতা 3 жыл бұрын
19:39
@youtubegarbage4u
@youtubegarbage4u 2 жыл бұрын
40 minutes for this tutorial?!? common man
Session Vs JWT: The Differences You May Not Know!
7:00
ByteByteGo
Рет қаралды 202 М.
Django 5.1 will be more secure by default
6:53
Dennis Ivy
Рет қаралды 9 М.
Don't look down on anyone#devil  #lilith  #funny  #shorts
00:12
Devil Lilith
Рет қаралды 47 МЛН
Good teacher wows kids with practical examples #shorts
00:32
I migliori trucchetti di Fabiosa
Рет қаралды 13 МЛН
Un coup venu de l’espace 😂😂😂
00:19
Nicocapone
Рет қаралды 12 МЛН
Authentication & Refreshing Tokens Implementation
2:09:53
Dennis Ivy
Рет қаралды 239 М.
Refresh Token Rotation With Next-Auth V5 || Managing Tokens With A Custom Backend
48:28
tapaScript by Tapas Adhikary
Рет қаралды 6 М.
The standard library now has all you need for advanced routing in Go.
13:52
Speed Up Your React Apps With Code Splitting
16:50
Web Dev Simplified
Рет қаралды 387 М.
🧯Неудачный день одного майора
0:44
arinanottoday
Рет қаралды 9 МЛН
Как назовем группу?)🤣
0:13
Dragon Нургелды 🐉
Рет қаралды 3 МЛН
Цыганка помогла мужику #shorts
0:38
FRANCH
Рет қаралды 6 МЛН