Тёмный

Refreshing Tokens With Axios Interceptors 

Dennis Ivy
Подписаться 212 тыс.
Просмотров 88 тыс.
50% 1

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/divanov11/refresh-...
Final Source code: github.com/divanov11/refresh-...
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

Развлечения

Опубликовано:

 

23 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 75   
@DennisIvy
@DennisIvy 2 дня назад
Don't forget to check out my Complete Django course: dub.sh/fkXTrSo
@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.
@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.
@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.
@stammeringprogrammer7535
@stammeringprogrammer7535 Год назад
That's my boy, I started following u since last year. You're awesome
@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.
@kleidilamka4518
@kleidilamka4518 Год назад
Great tutorial. Thank you for the quality content!
@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
@bismarcknyaboemomanyi6125
@bismarcknyaboemomanyi6125 2 года назад
thanks for the course dennis
@juhandvan
@juhandvan 2 года назад
Next time I hope you will guide how to handle possible errors using axios. Many thanks !!!
@user-ke4yx6uw1r
@user-ke4yx6uw1r 2 года назад
I wish I could give 10000000 likes. This is exactly what I needed
@haritpatel5001
@haritpatel5001 Год назад
Amazing video, learned a lot...
@serageibraheem2386
@serageibraheem2386 2 года назад
Great job buddy.. thanks
@andersonsimeon4172
@andersonsimeon4172 Год назад
This is legit the best video I found on this topic. Also, we use the same vscode theme.. lol
@AnthOo0ny
@AnthOo0ny 5 месяцев назад
what theme isit?
@andersonsimeon4172
@andersonsimeon4172 5 месяцев назад
@@AnthOo0ny It's called theme
@AnthOo0ny
@AnthOo0ny 5 месяцев назад
@@andersonsimeon4172 Thanks man
@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!
@kiprutobarno
@kiprutobarno Год назад
Great stuff!
@zahrareyhanian2859
@zahrareyhanian2859 2 года назад
Thak you for this awesome video.
@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
@gowthamtharan6818
@gowthamtharan6818 2 года назад
I think for this use case the custom redux middleware will help when multiple requests are sent at the same time
@Salmanfaris-pg2jw
@Salmanfaris-pg2jw 2 года назад
how we are getting data from authcontext to useaxios as it is out of the wrapper
@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
@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.
@abubakirmahkamov
@abubakirmahkamov 5 месяцев назад
pretty explanation.
@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.
@zamanEhsani
@zamanEhsani Месяц назад
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 ?
@aj14775
@aj14775 Год назад
the api should really be in the dependency array of the useeffect, but that would then cause an infinite re-render loop
@Ganapamanoj
@Ganapamanoj 17 дней назад
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.
@hodasj
@hodasj 2 года назад
what if the refresh token is expired? you haven't handled it right?
@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.
@alialavizadeh2775
@alialavizadeh2775 2 года назад
I wish you do one another video using redux it would amazing like this one
@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: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-vq861XoZI9k.html
@lifeofboringintrovert1350
@lifeofboringintrovert1350 2 года назад
Thank you
@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 Год назад
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); }; }, []);
@amosndonga.netcnextjsitsup5982
@amosndonga.netcnextjsitsup5982 2 года назад
Good stuff, man, can you do one on password reset plz
@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?
@mysteriousbillionaire7349
@mysteriousbillionaire7349 Год назад
Anything on social login please?
@kathir1188
@kathir1188 6 месяцев назад
i have one doubt for react native "jwt-decode" not working. Can anyone help in that issue?
@albythekkedan
@albythekkedan 5 месяцев назад
Becasue it is jwtDecode now
@baetraki7268
@baetraki7268 2 года назад
can you make this with redux please
@devdive24
@devdive24 2 года назад
I need your desktop background image
@TheGraphStyle
@TheGraphStyle Год назад
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 ;)
@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?
@paulobruno1267
@paulobruno1267 Год назад
Thank youuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
@NoName-pb5tl
@NoName-pb5tl 2 года назад
How can I prevent several refresh token requests?
@exequielarroyo
@exequielarroyo Год назад
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); }; }, []);
@blackpetergriffin179
@blackpetergriffin179 2 года назад
Man please Do Django authentication with email and otp verifcation
@mohamedyoussef8835
@mohamedyoussef8835 2 года назад
Awesome +++++++++++++++++++++++++++++
@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 Месяц назад
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 .
@safaemre9693
@safaemre9693 2 года назад
You cannot know your clients time is set correctly. Just because of this i prefer to use response interceptors.
@0xinconnu
@0xinconnu 2 месяца назад
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.
@user-ke4yx6uw1r
@user-ke4yx6uw1r 2 года назад
19:39
@GetBackTrolling
@GetBackTrolling 2 года назад
localstorage? really..
@youtubegarbage4u
@youtubegarbage4u 2 года назад
40 minutes for this tutorial?!? common man
Далее
Authentication & Refreshing Tokens Implementation
2:09:53
Выпускаем трек? #iribaby
00:14
Просмотров 311 тыс.
LLaMA 405b Fully Tested - Open-Source WINS!
10:02
Просмотров 3,5 тыс.
Speed Up Your React Apps With Code Splitting
16:50
Просмотров 374 тыс.
Axios Interceptors
9:22
Просмотров 4 тыс.
Django Skills Roadmap To Getting A Job
17:31
Просмотров 66 тыс.
Use Axios with React Hooks for Async-Await Requests
36:01
Role Based Navigation in React Native with Expo Router
25:41
This React UI Library is GAME CHANGER!
18:13
Просмотров 520 тыс.
ЧУВСТВУЕТЕ ГАБАРИТЫ?😂#shorts
0:14