Тёмный

🔑 JWT Authorization | Angular Router Guards | Token Refresh 

Dev Academy
Подписаться 6 тыс.
Просмотров 163 тыс.
50% 1

Join WebSecurity experts 👉 links.dev-academy.com/mcG
Article: links.dev-academy.com/kv4
Slack: bit.ly/2DWBU4V
Host: / bartosz_io
In this video, I will show you how to implement Angular application Authorization based on JSON Web Token abbreviated as JWT.
You will learn how to restrict access to the given parts of your application with Router Guards so that only authorized users would be able to access them.
Also, you will see how to intercept HTTP calls adding the access token required by the server.
Finally will learn why we need a refresh token and how to use it transparently for the user so that he is unaware of access token expiry and following refreshing process.
Music: www.bensound.com

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

 

7 июл 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 141   
@DevAcademyCom
@DevAcademyCom 5 лет назад
Sources: Angular: github.com/bartosz-io/jwt-auth-angular Node: github.com/bartosz-io/jwt-auth-node
@BimalDaslol
@BimalDaslol 5 лет назад
After trying whole day , taking examples from different websites, at last I found the video. Now all the issues are resolved. Thanks for sharing such a nice video. Keep it up ❤❤👌👌✔✔
@mgRamsesful
@mgRamsesful 4 года назад
¡Gracias desde México!
@ashishmishraakm
@ashishmishraakm 3 года назад
Thanks , It is good tutorial. Is there any way to refresh expired token instead of error 401 response.
@anat6152
@anat6152 5 лет назад
Excellent example. You safe my life, thank you very much.
@ssushantss
@ssushantss 5 лет назад
The explanation was on Point man..keep up the good work!
@DevAcademyCom
@DevAcademyCom 5 лет назад
Thank you!
@nishantsharma4313
@nishantsharma4313 5 лет назад
Its awesome. Thanks Bartosz
@juanchox0929
@juanchox0929 3 года назад
Excellent video! Thanks a lot for sharing your knowledge. I'll use this on a personal project
@user-vl1vl6yx7u
@user-vl1vl6yx7u 4 года назад
Thank you, man. This is very usefull for me. God bless you :)
@vaibhavarora7782
@vaibhavarora7782 3 года назад
great video. Before spending a day on this, just checked your video, and wow it saved me putting effort + I learned something easily here
@DevAcademyCom
@DevAcademyCom 3 года назад
Great! 🚀
@sushant9876
@sushant9876 5 лет назад
Really helpful. Thank you so much
@naveenamresh6339
@naveenamresh6339 5 лет назад
pls can u tell me how to logout when refresh token is expired
@hars9821
@hars9821 3 года назад
Simply awesome.. Thanks
@mauriceemmanuel5251
@mauriceemmanuel5251 3 года назад
loved this ❤️❤️
@SoundFilmDesign
@SoundFilmDesign 5 лет назад
This is great! Thank you. Would love to see the github repo :)
@DevAcademyCom
@DevAcademyCom 5 лет назад
Thank you very much! 😊 I will have an article for it with sources soon!
@belalsafy7993
@belalsafy7993 Год назад
Thank you very much, bro ❤
@WindsonViana
@WindsonViana 4 года назад
Great video. I have a question. In this example does the refresh token never expire?
@muhammadsherief3684
@muhammadsherief3684 3 года назад
Thanks that helped me a lot!
@DevAcademyCom
@DevAcademyCom 3 года назад
Great! Check wsa.dev 💪
@franck-cyrilkeulegbe6495
@franck-cyrilkeulegbe6495 4 года назад
Can you explain me how the method refreshToken() get executed without subscribe function?
@salimshaikh9807
@salimshaikh9807 4 года назад
Any solution refresh token is given the 401 status that time users go to login.
@87laus
@87laus 5 лет назад
Just had a look at this ..awesome. However, kindly revisit the logout endpoint. I noted that the implementation deletes the refresh token, but that does not necessarily stop the user from making requests to the end-point until the currently issued token expires
@DevAcademyCom
@DevAcademyCom 5 лет назад
The idea is to remove the token from the local storage, so that the requests will not be authorized after logout.
@naveenamresh6339
@naveenamresh6339 5 лет назад
@@DevAcademyCom pls can u tell me how to logout when refresh token is expired
@Kawtarslife
@Kawtarslife 4 года назад
Thank you so much
@DevAcademyCom
@DevAcademyCom 4 года назад
Welcome!
@anecha
@anecha 4 года назад
Good idea
@swapnanilgupta3046
@swapnanilgupta3046 3 года назад
One question - I can bypass the login screen by creating a Key-Value pair manually in localStorage named JWT_TOKEN. Now I know that the random number API call will fail because the token I have manually created in localStorage will be invalid, but still being able to bypass the login screen like this feels wrong. Is there any better way of implementing the isLoggedIn() method in auth.service?
@matteopellegrino5000
@matteopellegrino5000 3 года назад
Hi, i'm a beginner of Angular. How can i verify that the association between username and password? Is there any list of users that i have to write somewhere? Thx
@HuyNguyen-qe5zz
@HuyNguyen-qe5zz 3 года назад
thanks sir
@kamranabbasivlogs
@kamranabbasivlogs 3 месяца назад
Very nice
@DevAcademyCom
@DevAcademyCom 3 месяца назад
Thanks! Be sure to check out the new podcast :)
@andreasmerkle1011
@andreasmerkle1011 3 года назад
Isn't there something missing in "handle401Error ()"? If the API returns a 401 at "refreshToken" -> shouldn't that be caught - so that you can show an error message in the application? And shouldn't "isRefreshing" be set to false again?
@diegoarredondo1291
@diegoarredondo1291 4 года назад
Great video man, helped a lot!! Is there any example of the node auth file in python3?
@vahidsaebi5653
@vahidsaebi5653 4 года назад
Awesome
@mTz0KS43
@mTz0KS43 4 года назад
Hello, First of all great video, it helped me enough to understand key principles of working with a jwt token. Although I still got a question for you. Since I'm a frontend developer I'm a bit aware of how jwt logic in handled on the backend side. I have a situation where oauth/token isn't exposed directly to the client, but if I still try to reach the auth server in order to refresh the access_token, it requires the client_secret & client_id on which I don't have access from UI. It can be a lack of implementation on backend-side or i just missed some important parts. Thank you :)
@DevAcademyCom
@DevAcademyCom 4 года назад
Hi, join me on Monday and let's talk about it: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-p34F1qGAxBQ.html
@mTz0KS43
@mTz0KS43 4 года назад
@@DevAcademyCom Ok. Thank you! :)
@sourishdutta9600
@sourishdutta9600 4 года назад
Hi thanks for this awesome video , I have one question regarding this token security, where you save the token in front end so that no body can find this, local storage or session is not the right place to preserve the token as we can see this from browser console then where to store!? Thanks you so much..
@ahmedsaifulla5929
@ahmedsaifulla5929 4 года назад
Same doubt here
@bhanuprakashn6881
@bhanuprakashn6881 3 года назад
Why there are 2 network calls on the same name every time we make one call. One is 204 and other is 200. It is creating a problem in my backend. Is there any workaround for this?
@richardbravix8145
@richardbravix8145 2 года назад
when the refresh token dies the authGard doesn't go back to login page, how can we do that using your code ?
@bennythazhutha
@bennythazhutha 3 года назад
Hi, this video is amazing. I have only one doubt. when the refresh token is unauthorised or status 401, how or where to handle it ?
@DevAcademyCom
@DevAcademyCom 3 года назад
Hi, what would you like to do then?
@bennythazhutha
@bennythazhutha 3 года назад
@@DevAcademyCom redirect user to login page
@richardbravix8145
@richardbravix8145 2 года назад
@@bennythazhutha did u find out how can u do that ?
@mahmoud-kassem
@mahmoud-kassem 5 лет назад
Thank you for the great tutorial, I have problem when it refresh it sends the next request without the refreshed token that make 401, is there a solution to make it wait for the token before send again.
@mahmoud-kassem
@mahmoud-kassem 5 лет назад
It looks like I had conflict with the code in the part token.jwt, in my api it is token.access_token not token.jwt
@DevAcademyCom
@DevAcademyCom 4 года назад
Hi, did you follow the code from the tutorial?
@mahmoud-kassem
@mahmoud-kassem 4 года назад
@@DevAcademyCom Yes, I did, the problem was that I use a different API, it takes the old token to refresh itself and it doesn't need sprate token for refresh purpose only like in your example.
@DevAcademyCom
@DevAcademyCom 4 года назад
@@mahmoud-kassem You can always join our slack channel and provide your code snippets :) Somebody will try to help you.
@colincampbell2978
@colincampbell2978 3 года назад
I just have a question, is it wise or good practice to store it in local storage. Because it can easily be accessed by just using the browser console
@DevAcademyCom
@DevAcademyCom 3 года назад
Yes, you can access it by using the browser console but only on your own computer. The same happens to cookie session-id (even if stored in a cookie you can look up the contents with Dev Tools).
@phucnguyenvan4129
@phucnguyenvan4129 3 года назад
@@DevAcademyCom i have the same question, what happen if hacker attack by csrf (Cross-site Request Forgery) or XSS (Cross-site scripting) ?
@federicofernandez8008
@federicofernandez8008 3 года назад
@@phucnguyenvan4129 He could read both local storage or cookie I guess, so you are fuck*d anyway
@MostInterestingManInTheWrld
@MostInterestingManInTheWrld 4 года назад
Is local storage the safest place to put the tokens? I heard that it isn't
@DevAcademyCom
@DevAcademyCom 4 года назад
To make it safer, you can place tokens in HttpOnly cookie.
@alreadynuked
@alreadynuked 5 лет назад
When you refresh the token shouldn't you also refresh the refreshtoken? otherwise that could expire also and log out the user.
@DevAcademyCom
@DevAcademyCom 5 лет назад
Refresh tokens can have much longer validity time, so you don't have to refresh them every time.
@5kyn3t
@5kyn3t 4 года назад
but does this mean, that I would need to store an "expires date" for the refresh-token? In this case in-memory, but otherwise in a database...and in addition to the equals condition I would need a date-check in the 'refresh' function.. right?
@saimonldable
@saimonldable 3 года назад
Is it really necessary to implement that refreshTokenSubject when javascript is single threaded?. I mean even if the token.interceptor is handle as Singleton, the other request/queries (threads of execution at the end) should wait till the previous one has finished.
@heisenbergsk21
@heisenbergsk21 3 года назад
you don't want to let your token live for too long, do you ?
@saimonldable
@saimonldable 3 года назад
Token will live as long as unauthorized error status is returned. Isn't? Either way it continues to next.handle(req,header).
@heisenbergsk21
@heisenbergsk21 3 года назад
@@saimonldable with token refresh we can have expiration time very less for tokens as you don't want it to live it for too long and at the same time shouldn't ask users to login again in every 4 minutes . So that's why we need to implement refresh tokens
@saimonldable
@saimonldable 3 года назад
@@heisenbergsk21 I am not refering to the refresh token implementation itself, my doubt is with this handles401error where there are 2 paths. the first one leads to refresh token and the second one is implemented in case of having multiple requests/queries. My doubt is: Is it really necessary to implement this second path (else block instruction) where I am using a Behavior Subject object (the refreshTokenSubject)?.
@Alexmanyo1
@Alexmanyo1 4 года назад
What if the user messes with the refreshToken and the authentication token in the LS? How can this situation be handled, because with your implementation when the user logs out with the tempered refreshToken then it can't be deleted from the refreshTokens list in this case.
@DevAcademyCom
@DevAcademyCom 4 года назад
Yes, it will not be deleted. You could have a scheduler on your backend side that periodically removes outdated refresh tokens.
@Alexmanyo1
@Alexmanyo1 4 года назад
@@DevAcademyCom Thanks for the reply. The idea of implementing a scheduler is good, but I have the following suggestion: 1- if refreshtoken OR auth token is not correct/expired/has been tempered with, then sign out the user by clearing the LS without sending a request to /logout route. 2- in my MySQL DB I made a table for refreshtoken with corresponding userId in it (to link the logged in user with that refreshtoken). Also I don't care about auth token as it has short life time. 3- now that I have linked refreshtoken with a specific user, when the user logs in again I check whether that user had a refreshtoken linked to him/her. 4- if yes, I delete that token from DB and then give the user a new one and save that one in DB. So my question to you now is, is there any problem with this implementation (security problem or something), or is it Ok to implement?
@DevAcademyCom
@DevAcademyCom 4 года назад
@@Alexmanyo1That sounds good. The only concern is in point 1. Why would you perform this procedure if auth token expires? This case should trigger a regular refresh. As far I understand you want to deal with the situation when there is "phantom" refresh token due to user tempering with auth/refresh token.
@Alexmanyo1
@Alexmanyo1 4 года назад
@@DevAcademyCom Because I use the expired token to get, for example, the user ID to check it against the user ID linked to the refresh token in the DB. If that token has been tempered with (not expired as I said above, sorry about that) then I can't check whether the user is linked to that refresh token. Also because of this, is it better to store user ID in client and send it like that instead of using expired token to extract that info? In case a hacker steals the expired token with the refreshtoken for example.
@smileyakhi165
@smileyakhi165 4 года назад
Sir is this angular 8????
@le3ronjam3s43
@le3ronjam3s43 5 лет назад
I can see that you just recently started with the channel. With content as great as this, you will quickly climb to a high number of subs. I would only recommend you to give out content a bit faster. You will experience a much better growth. It's just a suggestion, I will obviously now benefit from it. :D Great Job on the logo and nice video organisation. p.s. I can see you are already planning blogs (written part of the code)
@DevAcademyCom
@DevAcademyCom 5 лет назад
Thank you for such a nice comment! I am planning to be more consistent and frequent with content creation! 😊 Have we met on Slack? :-)
@le3ronjam3s43
@le3ronjam3s43 5 лет назад
@@DevAcademyCom Nope I'm afraid I don't really use Slack :( I did run into an issue with my angular Auth. And I would like to ask you for some advice. What happens if the refresh token times out as well? I am not sure how to handle that. Please help.
@eriic504
@eriic504 3 года назад
Please explain about mapTo(true) and return of(true) at 6:03. Why don't you use return of(true) instead of mapTo(true)?
@DevAcademyCom
@DevAcademyCom 3 года назад
Because in that place we are inside of the `pipe()` and we need a RxJS operator. How would you place `return` statement there? :)
@eriic504
@eriic504 3 года назад
@@DevAcademyCom Many thanks
@adityadhanrajtiwari7939
@adityadhanrajtiwari7939 3 года назад
accent is amazing
@DevAcademyCom
@DevAcademyCom 3 года назад
🤡👍
@DanielPradoBurgos
@DanielPradoBurgos 2 года назад
Hey qq, isn't a security hole to store the token where JS can access it?
@DevAcademyCom
@DevAcademyCom 2 года назад
Not really. I explained that in more detail here: dev-academy.com/angular-user-login-and-registration-guide-cookies-and-jwt/
@DanielPradoBurgos
@DanielPradoBurgos 2 года назад
@@DevAcademyCom gotcha, yeah httponly cookies would do the trick perfectly!
@mehdiSupp
@mehdiSupp 4 года назад
Since the refreshToken doesn't expire, a hacker can use it whenever he wants access by calling /refresh without the need to log in... right ?
@DevAcademyCom
@DevAcademyCom 4 года назад
Basically yes, but refreshToken can be revoked on the server. Tokens are like passwords, should be kept secure and secret.
@DevAcademyCom
@DevAcademyCom 4 года назад
Another way to prevent this situation is Refresh Token Rotation. It basically means every time you refresh (let's say every 10 minutes), you generate a new Refresh Token and the old one becomes invalid.
@mrtraveller2679
@mrtraveller2679 4 года назад
@@DevAcademyCom what if someone steal refresh token and he also know how to rotate refresh token before expires, how to handle this situation?
@DevAcademyCom
@DevAcademyCom 4 года назад
@@mrtraveller2679 How can someone know how to rotate?
@smileyakhi165
@smileyakhi165 4 года назад
Sir is this angular 8
@ttma1046
@ttma1046 5 лет назад
I dont see "refreshTokens" is an "array", it's just an object.
@DevAcademyCom
@DevAcademyCom 5 лет назад
You are right! Thanks for your catchy eye!
@AnkitYadav-xd3pi
@AnkitYadav-xd3pi 3 года назад
Do we need to call service for log out Or we can remove from local storage? 🤔
@lakshmana487
@lakshmana487 3 года назад
Removing from local storage is good enough, because rest services you don't create session on server side.
@swapnanilgupta3046
@swapnanilgupta3046 3 года назад
I think we have to call the logout service, because the way this api is designed, the refresh token needs to be deleted from the server.
@jeffreyfung2263
@jeffreyfung2263 4 года назад
Does anyone know the password @ 1:38? (Thanks in advance)
@christianaustria741
@christianaustria741 5 лет назад
any github link?
@DevAcademyCom
@DevAcademyCom 5 лет назад
Yes! Soon!
@dzsi1994
@dzsi1994 5 лет назад
And what if the refreshToken request fails?
@DevAcademyCom
@DevAcademyCom 5 лет назад
Then we should log out the user.
@user-yt7rd9fq7q
@user-yt7rd9fq7q 5 лет назад
and how? how do we know it's refreshToken request failed?
@letok2871
@letok2871 5 лет назад
@@user-yt7rd9fq7q this is my solution. token.interceptor.ts : return next.handle(request).pipe( catchError(error => { if ( error instanceof HttpErrorResponse && error.status === 401 && error.error.refreshToken ) { this.authService.logout().subscribe(success => { if (success) { this.router.navigate(['/login']); } }); return throwError(error); } else if (error instanceof HttpErrorResponse && error.status === 401) { return this.handle401Error(request, next); } else { return throwError(error); } }) ); server side, index.js app.post('/refresh', function(req, res) { const refreshToken = req.body.refreshToken; if (refreshToken in refreshTokens) { const user = { username: refreshTokens[refreshToken], role: 'admin' }; const token = jwt.sign(user, SECRET, { expiresIn: 600 }); res.json({ jwt: token }); } else { res.status(401).json({ refreshToken: true }); } });
@naveenamresh6339
@naveenamresh6339 5 лет назад
@@DevAcademyCom please give an answer to it.... catchError is not working for that pipe...... Pls how to logout pls reply
@sajeebchandansaha6378
@sajeebchandansaha6378 2 года назад
Great Video. This helped me a lot. Thank you.
@DevAcademyCom
@DevAcademyCom 2 года назад
Great! Did you implement it in your project? :)
@sajeebchandansaha6378
@sajeebchandansaha6378 2 года назад
@Dev Academy Yes. Already and extended it to as per my requirement.
@shubhamsharma5226
@shubhamsharma5226 4 года назад
Hey invite link of slack is not active please help me
@DevAcademyCom
@DevAcademyCom 4 года назад
Hey, it should be fixed now. Does it work for you?
@shubhamsharma5226
@shubhamsharma5226 4 года назад
@@DevAcademyCom your link for invite to stack have been expired
@DevAcademyCom
@DevAcademyCom 4 года назад
@@shubhamsharma5226 Check the new link on the website.
@bhmanikantaraju3656
@bhmanikantaraju3656 3 года назад
can u send me api code to learn little bit eassy
@mortezabehboodian5758
@mortezabehboodian5758 4 года назад
9:09 HWT?!
@DevAcademyCom
@DevAcademyCom 4 года назад
Hahaha! My mistake! 🤣
@cristiantorres3303
@cristiantorres3303 5 лет назад
how the fuck I start creating the guard with angular cli I came here to do that. it is a service can I just say ng generate service auth.guard ?
@ernestomunera8235
@ernestomunera8235 4 года назад
HI! When you said Local Storage is a cache variable? ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-F1GUjHPpCLA.html
@MsSoldadoRaso
@MsSoldadoRaso 2 года назад
😂😂 I can send any invalid token, and then I intercept the * RESPONSE * traffic from the backend (all this can be done with Burpsuite) then I modify the response as if it were a simple notepad making it look like that token has been valid with a status 200 and also add some valid headers to that response, doing this angular will see that the token has been "valid" and would give me access to pass the Guard. Therefore protecting routes on the client side is not secure. The only thing that can be protected are things on the server side, on the client protecting something is a 💩
@DevAcademyCom
@DevAcademyCom 2 года назад
Yes, that is correct. Who said that this cannot be bypassed? I think you missed the point here. 😋 You can even download the whole JS bundle from the server and read it and stick a "HACKER" on your forehead... 😂
@MsSoldadoRaso
@MsSoldadoRaso 2 года назад
@@DevAcademyCom angular guards its a shit🤣🤣😂
@DevAcademyCom
@DevAcademyCom 2 года назад
It's mainly for UX :-)
@technicalbabu814
@technicalbabu814 3 года назад
not working bro
@DevAcademyCom
@DevAcademyCom 3 года назад
No problem bro 💪
@MrZajic_
@MrZajic_ 4 года назад
If someone can steal jwtToken (validity eg 5 minutes), then he will steal refreshToken (validity eg 5 days) too. Yes, you can use refresh rotation token. But why? Attacker only repeat attack and steal new. And revoke refresh token? I think its too late for this solution. Attacker done his job.
@CianMcsweeney
@CianMcsweeney 4 года назад
If the attacker has the access token that does not give them the refresh token. To minimise the impact of an attacker gaining the access token you can set the access token to be extremely short lived, e.g access token expires every 60 seconds. No auth system will ever be infallible, but using access/refresh tokens along with ssl/tls certs is one of the most secure methods available. Since the access token is nearly impossible to be stolen via man in the middle attacks, and that it is only stored in the clients memory, it is incredibly unlikely that it'll be stolen unless there is a very directed and purposeful attack on one specific user. A more advanced system to deal with that unlikely scenario would be to have some sort of heuristic algorithm that detects unusual behaviour, e.g requests coming from locations the user has never logged in from before along with other metrics. That topic is well out of the scope of what most small web apps will ever need to implement.
@MrZajic_
@MrZajic_ 4 года назад
Thanks for response. That sounds logical. I only don't understand have jwtToken && refreshToken saved in localStorage both.
@CianMcsweeney
@CianMcsweeney 4 года назад
@@MrZajic_ yeah saving in local storage is a bad idea, the access token shouldn't stored at all, and the refresh token should be in a Http-Only cookie, this stops it being accessible through scripts. Another option for web apps is the implicit flow, which is another topic entirely 😊
@mrtraveller2679
@mrtraveller2679 4 года назад
@@MrZajic_ do you suggest any other options which is more secure for client side storage for accesstoken and refresh token
@Justaszz
@Justaszz 3 года назад
I don't think its safe to store JWT in localStorage
@DevAcademyCom
@DevAcademyCom 3 года назад
If your application has an XSS vulnerability, then yes. Everything has its pros and cons. The thing is to be aware of them. You can learn here: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-fIaJDU-jGrA.html
@Justaszz
@Justaszz 3 года назад
@@DevAcademyCom besides the localstorage, what would be the best to store jwt access and refresh tokens?
@DevAcademyCom
@DevAcademyCom 3 года назад
@@Justaszz in memory
@Justaszz
@Justaszz 3 года назад
@@DevAcademyCom and if user refreshes page, how to keep him logged in?
@Godwin335
@Godwin335 5 лет назад
intro sound sucks.
@DevAcademyCom
@DevAcademyCom 5 лет назад
You can always mute the whole video.
@jonhylight
@jonhylight 4 года назад
That intro is not volume balanced man...I disliked it for that reason alone. Is not healthy to have a intro like that. The rest of the video is good. I would like and advise you change your intro sound.
@smileyakhi165
@smileyakhi165 4 года назад
Sir is this angular 8
Далее
JWT Hacking (JSON Web Token)
35:24
Просмотров 3,6 тыс.
Top 7 RxJS Concepts for Angular Developers
7:19
Просмотров 197 тыс.
What Is JWT and Why Should You Use JWT
14:53
Просмотров 1,1 млн
Asp.Net Core Web API - Login and Logout with Angular 7
1:32:19
WTF is "Zone.js" and is it making your app slow?
13:21
how to use JWT token in Angular 17
47:28
Просмотров 9 тыс.