This is great! One of the best tutorials I've seen on this. I wondred, whether in your series, you might consider teaching how to implement login with email validation, but instead of angular receiving the tokens, a Spring BFF, with say an Auth Provider like KeyCloak...
Great Bouali Ali. I did watch your previous videos and I read the comments on the Refresh token. And here you go everyone he delivered as you asked for. Such an inspiration. Keep up the great work.
One of the best trainers for sure. I would just like to see your way of doing this authentication with angular; because your way is always very optimal and understandable.
Thank you for nice tutorial. But may i ask you a question that should we save the refresh token in db like we save the access token? if not (only store access token in cookie or anything regarding to client-side), what will happen, it it secured like when we log out the refresh token will be revoked in some how? Thank you in advanced!
Again a great content. But I have two question to it: 1. In the method refreshToken why we use ObjectMapper instead of returning the AuthorizationResponse like we do it if we register or log in? 2. If I understand it correctly, the whole point of a refresh token is to send a new access token, if the old is no more valid. I miss this workflow from the video. I mean there should be a common method, which checks, if the access token belongs to the right user, but it is expired, and if so, then call the refreshToken method and with the new access token let the user access the restricted resource. Because now if we hit the demo controller, we get only a token expired exception. And I think, in this case, we should call the refreshToken method. And this generally for all secured endpoint. Maybe in a common exception handling, where we catch the token expired exception. This would be a kind of silent re-login. What do you think?
Thank you for the feedback. here are the answers to you questions: 1- When I create new videos, I always try to show many ways of doing things because I believe that someone would need it one day 2- The refresh token is also a JWT token which signed and assigned to the connected user. Refreshing the token should be always done by the API client (frontend, mobile App, ...) not the API it self
Hello Sr. Thanks for your content. I was wondering: Do I have to persist the token in the data base if I want the functionality of refresh-token? o are there any other althernatives?
How to revoke tokens? The whole video is almost useless if I don't know how to revoke tokens... It would take you a minute to show that, but it will take me 15 minutes to find another video that explains it and integrate it. Other than that, video is very helpful and well made.
I'm actually speechless Ali, thank you so so much for your effort in providing such awesome content. And please if you'll make a video that dive into CSRF it'll be really useful, I mean the CSRF is important when it comes to security right. Because most of the video out there just disable it and then move on, without giving why and what should be the best practices on that at the dev environment. Thank you once again for the contents ❤❤❤
First of all thank you for providing such a explanatory session but may i ask you one thing that you are generating the access token and refresh token with same method called build token where the only thing differs is the expiration. So my concern is that with this refresh token the user should not be able to access the endpoints other than refresh-token. So how is it made possible? I didn’t see any information regarding that. Hope you will help me with this soon.
Hello Bouali. Thanks for this video. Which would you say is the more efficient? Implementing JWT authentication using filters or implementing it on the controller and service layers?
Thank you very much for this wonderful video tutorial Is there no need to save the refresh token in the database? Because we do not store the refresh token in the code
Please correct me if I am wrong: For the front end I should be using the refresh token endpoint whenever I receive a 403 when using the access token then resend the same request with the new access token. And if I receive a 403 on the refresh token endpoint that's when I log out the user from my app (I am using a mobile app for the front end and spring boot for the backend)
Frist of all, thank you so much for these great videos. I have a question. I've written all the codes with you. At the end, i can register for a new user and get 2 tokens, also can get 200 from demo-controller request. But when i send "refresh-token" request, i doesn't send me token. I just get 200 message. I also had this problem with "authenticate" endpoint, mostly returns 403. What could be the reason? Thank you.
Thank you for this tutorial. i have a doubt please clear my doubt. i implement this code in my local and i set both expiration and refresh-token expiration as 1 minute. but i unable access to demo api. after i change refresh-token expiration as 7days i able to access demo api and after 1 minute it is expired and i generate new access token from the refresh token. that new access token also access that demi api without authenticate. my question is how is possible to access demo api with out authenticate(not hit the authenticate api).
I think yes. As I mentioned in my latest videos, it better to use an auth provider like keycloak (opensource) and avoid all this manual handling. I will release a full integration video soon for keycloak
First of all, your contents are awesome, thank you for that. Secondly, I have a question about why we dont save a refreshToken to the DB also, in case we want to use it later after accessToken is expired for example in 1 day ? I mean how this aproach will be usefull in fullstack app when we call it from the client side ? Again, thank you so much!!!
Thank you so much for your video. i have 1 question : if i already have an unexpired accesstoken and send it to the refreshtoken endpoint will i get a new access token and i will have more time to use it. If so, I only need 1 access token and I will be able to log in forever. please help me explain. sorry if there's something wrong
@@BoualiAli sorry pro, because i'm not good at english. I mean after call endponit /authenticate , there is accessToken and refeshToken and when I call endpoint /refreshToken the variable I pass to api is accessToken with time, the response will still return new accessToken , I got such bug because I didn't check whether the token sent is a refresh token or an access token at the /refreshToken endpoint
Hello, I am a student who is taking a lecture in Korea. Thanks to the video, I am studying jwt well. I'm leaving a question because I'm curious about the video. 1. I processed it in the filter when I logged out, but I wonder why you processed it in the filter instead of going to the service layer. 2. And I was wondering if I should process it through filter even if my access token has expired and I need to reissue it with refresh token. Or I wonder if it should be handled by the service layer. I'd appreciate it if you could answer. In conclusion, I wonder if all the authentication/authorization procedures are handled by the filter or by going to the controller -> service layer.
Hello, here are the answers to your questions: 1- because the filter is the first layer to receive the request 2- the security filtering / checking should be done on the filter layer
We are doing all stuff manually, like register and login and logout and refreshing tokens but I bet it's not how it works in a real world, right? So we have to implement some sort of redirection or what? I mean if a user have access and refresh tokens and when the 1st one expires he won't reach secured endpoints.. then what he gets? Will he be redirected to login screen or when access token is expired and when user tries to get to secured endpoint he will be redirected to someting "/refresh-token" url and then redirected to url he wanted to get? But what if our user is not a real person who has all those frontend possibilities (like buttons to logout, login screen, browser will store those tokens and manipulate it without user knowing what's even going on and so on). What is our user is another api? What happens then? Everything we did in postman must be implemented in that app's code like to get token after registration, store it somewhere too and then provide us with those tokens so we can compare with what we (our api) have in our database, right? Also, seems like those banking mobile apps don't use jwt or anything like that since I've heard that access tokens have pretty small expiration period like 15 mins which means that after it expires I would have to authenticate again but I can use those apps as long as I want as long as I stay active. What is the mechanism behind those apps then? Sessions that expires after a set period of beind idle? Sorry for such messy message, I'm a bit excited after this video and have so much questions. PS. we've made a separate entity for token with its state and we're storing it in our database, do we move from stateless to stateful now?
For the first part of your question: this API is designed to be consumed by any client (API, frontend, ...) The client should handle the token expiration and refreshing the token because we need to stick to the REST architecture. For Machine To Machine (api to api) you can implement an other mechanism like API secrets / tokens Also storing the token does not make your API stateful because it is all about saving the state of the client in your backend, which is not the case for our REST API
Hello Ali. After using the Refresh Token, don't we need to generate the Refresh Token again? So, wouldn't we reset the lifetime of the Refresh Token in this way?
its a great video .really helpfull Ali but i have an doubt plz clarify me .i implement your code everything including refresh token and access token when i post data through postman tool it showing response 200k but body of response showing me as accessToken:null, refresshToken:null.I dont know how to solve pls reply me
Your issue was 8 months ago but I just ran into this same problem so if anyone runs into this as well then check your if() condition for the userEmail inside of the AuthenticationService refreshToken() function. Remove the SecurityContextHolder check if you still have it; it should only be if userEmail is null
@@BoualiAli Okay, that is what I assumed, I thought there was some specification outside the .yml to say the JWT bearer was expiring every minute. It worked just fine with the .yml was modified to a lower time-frame.
incase of token expired what excpetion must be thrown in order to the client(caller) will call the refresh token and by that the client can differentiate between expired token and wrong token?
I really don't remember the exact exception class name. pass an expired / wrong token and check the console and then add the exception handling for it. You can check the Exception handling video that I already posted before
Why acces token should expire after 1 minute, is it preconfigured? It seems that my acces token doesnt expire and i can acces demo-controller even after 10 min, does someone have similar problem or can help ?
this is so wrong in so many ways, starting from implementing your own jwt auth flow instead of using spring security's provided oauth2, using symmetric encryption instead of assymetric one (i assume you're using HS256), while the key itself is just a random (not cryptographically secure) string etc. The code itself is bad, e.g. using objectMapper to print the response is just a wtf moment. There's a good OWASP JWT cheat sheet, which I recommend to anyone stumbling across this poor 'guide' as well as comparing them to session based authentication, which you probably want to check first.
COUPON Code: *EARLYBIRD20* => Spring Data J PA course: aliboucoding.com/p/the-full-guide-to-master-spring-boot-data-jpa
Гарно освітлена тема. Дякую
My pleaser!
This is great! One of the best tutorials I've seen on this. I wondred, whether in your series, you might consider teaching how to implement login with email validation, but instead of angular receiving the tokens, a Spring BFF, with say an Auth Provider like KeyCloak...
شكرا جزيلا على مجهودك. اتمنى ان لا تنسى المجتمع العربي من شرحك
Great Bouali Ali. I did watch your previous videos and I read the comments on the Refresh token. And here you go everyone he delivered as you asked for. Such an inspiration. Keep up the great work.
Much appreciated
Finished your spring security course and i was wondering how to implement refresh tokens. You read my mind. Thanks for this
One of the best trainers for sure.
I would just like to see your way of doing this authentication with angular; because your way is always very optimal and understandable.
Happy you liked it
I'm working on it and it will be released soon
you wait for JWT and aouth2 authentication together implementations.
thank you for sharing.
You are welcome
This video is very useful, thank you very much!!
Glad it was helpful!
Thank you for nice tutorial. But may i ask you a question that should we save the refresh token in db like we save the access token? if not (only store access token in cookie or anything regarding to client-side), what will happen, it it secured like when we log out the refresh token will be revoked in some how? Thank you in advanced!
I had the same doubt. Is this okay to save the refresh token in DB instead of access Token ?
Again a great content. But I have two question to it:
1. In the method refreshToken why we use ObjectMapper instead of returning the AuthorizationResponse like we do it if we register or log in?
2. If I understand it correctly, the whole point of a refresh token is to send a new access token, if the old is no more valid. I miss this workflow from the video. I mean there should be a common method, which checks, if the access token belongs to the right user, but it is expired, and if so, then call the refreshToken method and with the new access token let the user access the restricted resource. Because now if we hit the demo controller, we get only a token expired exception. And I think, in this case, we should call the refreshToken method. And this generally for all secured endpoint. Maybe in a common exception handling, where we catch the token expired exception. This would be a kind of silent re-login. What do you think?
Thank you for the feedback.
here are the answers to you questions:
1- When I create new videos, I always try to show many ways of doing things because I believe that someone would need it one day
2- The refresh token is also a JWT token which signed and assigned to the connected user. Refreshing the token should be always done by the API client (frontend, mobile App, ...) not the API it self
Hello Sr. Thanks for your content.
I was wondering: Do I have to persist the token in the data base if I want the functionality of refresh-token? o are there any other althernatives?
No need
Thank you, I will use it for my university project. portuguese here
Best of luck!
How to revoke tokens? The whole video is almost useless if I don't know how to revoke tokens... It would take you a minute to show that, but it will take me 15 minutes to find another video that explains it and integrate it. Other than that, video is very helpful and well made.
check the logout video and you will get your answer
@@BoualiAli I know, but I don't want to unnecessary waste about 15 minutes for that.
@@vojinkarisik1554 searching in the channel takes 1 minute
Great Work
I'm actually speechless Ali, thank you so so much for your effort in providing such awesome content.
And please if you'll make a video that dive into CSRF it'll be really useful, I mean the CSRF is important when it comes to security right.
Because most of the video out there just disable it and then move on, without giving why and what should be the best practices on that at the dev environment.
Thank you once again for the contents ❤❤❤
Thank you, I will
@@BoualiAli Thank you Sir, JazaakAllahu khairan
Good concept explain by you sir 😊
Happy you liked it
First of all thank you for providing such a explanatory session but may i ask you one thing that you are generating the access token and refresh token with same method called build token where the only thing differs is the expiration. So my concern is that with this refresh token the user should not be able to access the endpoints other than refresh-token. So how is it made possible? I didn’t see any information regarding that. Hope you will help me with this soon.
i guess you can set a claims inside the token (ex : token type -> refreshToken or accessToken then you can check in the backend)
Thanks for this sir ! Please do we have a course on sending email when a user creates an account🤩🙏
I have one on my website
Aliboucoding.com/courses
ty very match from Russia
My pleasure 😇
Hello Bouali. Thanks for this video. Which would you say is the more efficient? Implementing JWT authentication using filters or implementing it on the controller and service layers?
first option is better
Nicely explained 👌
Glad you liked it
You're the Best
Thank youu 🙏
Grande ali😎
Thank you 🙏
Great video ! thanks for sharing this!
Happy you liked it
Thank you very much for this wonderful video tutorial
Is there no need to save the refresh token in the database?
Because we do not store the refresh token in the code
Happy you liked it!
Storing the token was an approach to implement logout (just an example)
Please correct me if I am wrong: For the front end I should be using the refresh token endpoint whenever I receive a 403 when using the access token then resend the same request with the new access token. And if I receive a 403 on the refresh token endpoint that's when I log out the user from my app (I am using a mobile app for the front end and spring boot for the backend)
as far as i know you could use a setInterval function that will execute code after 1 min or it depends on your access token.
This is a great content, thank you so so much.
Glad you enjoyed it!
Frist of all, thank you so much for these great videos. I have a question. I've written all the codes with you. At the end, i can register for a new user and get 2 tokens, also can get 200 from demo-controller request. But when i send "refresh-token" request, i doesn't send me token. I just get 200 message. I also had this problem with "authenticate" endpoint, mostly returns 403. What could be the reason? Thank you.
Thank you very much sir.
Most welcome
Thank you for this tutorial.
i have a doubt please clear my doubt.
i implement this code in my local and i set both expiration and refresh-token expiration as 1 minute. but i unable access to demo api. after i change refresh-token expiration as 7days i able to access demo api and after 1 minute it is expired and i generate new access token from the refresh token. that new access token also access that demi api without authenticate.
my question is how is possible to access demo api with out authenticate(not hit the authenticate api).
thank you!
You're welcome!
Hello,
You arranged the jwt-expiration for a day in application.yml but at the end it expired in a minute. Did i miss sth or what?
thanks,🤗
Welcome 😊
thank you for the great content. Can you please make a tutorial about online payement with spring boot and angular . TKU
aliboucoding.com/p/spring-boot-paypal-payment-integration
i love it
I'm glad you like it
Best !
Glad you think so!
Hi, i have question, if someone pass refresh token instead of access Token, it will also work. then what is purpose of creating two token ?
I think yes.
As I mentioned in my latest videos, it better to use an auth provider like keycloak (opensource) and avoid all this manual handling.
I will release a full integration video soon for keycloak
Mashallah brother … thank you !!
My pleasure
Great content as always :) I'm still waiting for the Swagger interation. I hope you still find time for it :)
Coming really soon.
First of all, your contents are awesome, thank you for that.
Secondly, I have a question about why we dont save a refreshToken to the DB also, in case we want to use it later after accessToken is expired for example in 1 day ? I mean how this aproach will be usefull in fullstack app when we call it from the client side ?
Again, thank you so much!!!
I already mentioned that you can also save the refresh token and perform a second level of validation too
thank you very much
You are welcome
25:20 Can add " response.setContentType("application/json"); " before " new ObjectMapper().writeValue(response.getOutputStream(), authResponse); "
Thanks
Thank you so much for your video. i have 1 question : if i already have an unexpired accesstoken and send it to the refreshtoken endpoint will i get a new access token and i will have more time to use it. If so, I only need 1 access token and I will be able to log in forever. please help me explain. sorry if there's something wrong
for the refresh, you need the refresh token which hase a longer expiry period but it is not for ever (depending on you implementation)
@@BoualiAli sorry pro, because i'm not good at english. I mean after call endponit /authenticate , there is accessToken and refeshToken and when I call endpoint /refreshToken the variable I pass to api is accessToken with time, the response will still return new accessToken , I got such bug because I didn't check whether the token sent is a refresh token or an access token at the /refreshToken endpoint
Hello, I am a student who is taking a lecture in Korea.
Thanks to the video, I am studying jwt well.
I'm leaving a question because I'm curious about the video.
1. I processed it in the filter when I logged out, but I wonder why you processed it in the filter instead of going to the service layer.
2. And I was wondering if I should process it through filter even if my access token has expired and I need to reissue it with refresh token. Or I wonder if it should be handled by the service layer.
I'd appreciate it if you could answer.
In conclusion, I wonder if all the authentication/authorization procedures are handled by the filter or by going to the controller -> service layer.
Hello, here are the answers to your questions:
1- because the filter is the first layer to receive the request
2- the security filtering / checking should be done on the filter layer
Good content i like it it really helped me...
is it possible to combine Oauth2 with jwt in the same spring application???
Really happy you liked it
Yes it is possible of course
👍👍👍👍
We are doing all stuff manually, like register and login and logout and refreshing tokens but I bet it's not how it works in a real world, right? So we have to implement some sort of redirection or what? I mean if a user have access and refresh tokens and when the 1st one expires he won't reach secured endpoints.. then what he gets? Will he be redirected to login screen or when access token is expired and when user tries to get to secured endpoint he will be redirected to someting "/refresh-token" url and then redirected to url he wanted to get?
But what if our user is not a real person who has all those frontend possibilities (like buttons to logout, login screen, browser will store those tokens and manipulate it without user knowing what's even going on and so on). What is our user is another api? What happens then? Everything we did in postman must be implemented in that app's code like to get token after registration, store it somewhere too and then provide us with those tokens so we can compare with what we (our api) have in our database, right?
Also, seems like those banking mobile apps don't use jwt or anything like that since I've heard that access tokens have pretty small expiration period like 15 mins which means that after it expires I would have to authenticate again but I can use those apps as long as I want as long as I stay active. What is the mechanism behind those apps then? Sessions that expires after a set period of beind idle?
Sorry for such messy message, I'm a bit excited after this video and have so much questions.
PS. we've made a separate entity for token with its state and we're storing it in our database, do we move from stateless to stateful now?
For the first part of your question: this API is designed to be consumed by any client (API, frontend, ...)
The client should handle the token expiration and refreshing the token because we need to stick to the REST architecture.
For Machine To Machine (api to api) you can implement an other mechanism like API secrets / tokens
Also storing the token does not make your API stateful because it is all about saving the state of the client in your backend, which is not the case for our REST API
Ok, we store all user’s tokens in the db, but when do we need to read them from db? You only read them for update when revoking tokens…
when it comes to front end what is the best and secured way to store the refresh token?
session and local storage are perfectly fine
I am wondering; if the jwtToken is stateless, why do we need to save it in the database?
I explained that in the logout video.
It is just an approach (maybe not the best) to implement a logout mechanism
@@BoualiAli Thank you for your quick response. I understand. Do you recommend any other approach from your personal experience?
Hi I think a better way to do it and the way I see it done by decoding other library token is by adding a token_type: refresh
Hello Ali. After using the Refresh Token, don't we need to generate the Refresh Token again? So, wouldn't we reset the lifetime of the Refresh Token in this way?
If you also regenerate the refresh token each time, it will never expire which is not relevant as I explained
thanks
You're welcome!
I see you set the expiration time of the access token to 1 day, so why when using postman the expiration time is 60s ?
Just to demonstrate.
I cannot wait one day until the token is expired to showcase it lol
@@BoualiAli will token expire if keep on using API?
its a great video .really helpfull Ali but i have an doubt plz clarify me .i implement your code everything including refresh token and access token when i post data through postman tool it showing response 200k but body of response showing me as accessToken:null, refresshToken:null.I dont know how to solve pls reply me
Check if you set correctly the values. Follow the same steps as I did
Your issue was 8 months ago but I just ran into this same problem so if anyone runs into this as well then check your if() condition for the userEmail inside of the AuthenticationService refreshToken() function. Remove the SecurityContextHolder check if you still have it; it should only be if userEmail is null
Small typo at the end; I meant not equals null, so: if(userEmail != null)
Why does your access_token expire for the demo controller after 1 minute but the application.yml is set to a day?
Just for the demo. It is hard to wait a day until the token expires to demonstrate
@@BoualiAli Okay, that is what I assumed, I thought there was some specification outside the .yml to say the JWT bearer was expiring every minute. It worked just fine with the .yml was modified to a lower time-frame.
why am i getting error 500 when the jwt goes expired ?
Hi, i dont need to store the refreshToken in the database?
Not necessarily in a database but you need to save it to a storage system / cache like redis
incase of token expired what excpetion must be thrown in order to the client(caller) will call the refresh token and by that the client can differentiate between expired token and wrong token?
I really don't remember the exact exception class name.
pass an expired / wrong token and check the console and then add the exception handling for it.
You can check the Exception handling video that I already posted before
please sir make a video for jwt exception handling
Already uploaded.
Check the playlist
Why acces token should expire after 1 minute, is it preconfigured? It seems that my acces token doesnt expire and i can acces demo-controller even after 10 min, does someone have similar problem or can help ?
if you use these 86400000, it will expire after 1 day
How to handle refresh token expired?
Same way as the normal token
Ali i hope ure swimming in fucking money my guy. Ure insane
this is so wrong in so many ways, starting from implementing your own jwt auth flow instead of using spring security's provided oauth2, using symmetric encryption instead of assymetric one (i assume you're using HS256), while the key itself is just a random (not cryptographically secure) string etc. The code itself is bad, e.g. using objectMapper to print the response is just a wtf moment. There's a good OWASP JWT cheat sheet, which I recommend to anyone stumbling across this poor 'guide' as well as comparing them to session based authentication, which you probably want to check first.
do you have some recomendation instead that guide?
Plz try for the forget Password
Sure I will do
@@BoualiAli thank plz
it does not make sense,
when you refresh token you have to refresh both tokens as well, not only access_token
really?
So wha is it called refresh token if you have to refresh it within the real token