Spring Security - Refresh token

Поділитися
Вставка
  • Опубліковано 23 лип 2024
  • Buy me a coffee: ko-fi.com/boualiali #githubactions #cicd #spring #learning #springboot #springtutorial #springsecurity #developpement #java #arraylist #linkedlist #springdatajpa #querybuilder #aliboucoding #alibou #validation #mongodb #springboot_3 #oauth2 #security #reactive #springreactive
    In this tutorial, we demonstrate how to implement a refresh token mechanism in a Spring Boot application secured with JSON Web Tokens (JWT). Refresh tokens improve the security and user experience of your application by allowing clients to request new access tokens without requiring users to re-authenticate every time their access token expires.
    By the end of this video, you'll have a solid understanding of how to implement a refresh token mechanism within your Spring Boot application, providing a more secure and seamless experience for your users.
    Don't forget to like, comment, and subscribe to our channel for more in-depth tutorials on Spring Boot, JWT authentication, and other programming topics!
    👉🏻 Source code: github.com/ali-bouali/spring-...
    Don't Forget to
    ===========================================
    💯 Free courses here: aliboucoding.com
    💯 Subscribe to the youtube channel
    💯 Join our Discord Community - / discord
    💯 Join our Facebook Group - / 589612651142975
    💯 Join our Instagram: / alibou_coding
    Table of content
    00:00 Intro
    01:00 What is refresh token
    03:47 Extend the AuthenticationResponse
    06:07 Extract JWT properties
    09:31 Create refresh token method
    12:07 Adjust the register and authenticate endpoints
    14:10 Add refresh token endpoint
    14:44 Implement the refresh token mechanism
    22:08 Revoke the newly generated token
    22:56 Test the changes
    35:49 Thanks for watchin

КОМЕНТАРІ • 124

  • @BoualiAli
    @BoualiAli  11 місяців тому +4

    COUPON Code: *EARLYBIRD20* => Spring Data J PA course: aliboucoding.com/p/the-full-guide-to-master-spring-boot-data-jpa

  • @surge6652
    @surge6652 Рік тому +1

    Finished your spring security course and i was wondering how to implement refresh tokens. You read my mind. Thanks for this

  • @firibuanyass
    @firibuanyass Рік тому +3

    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.

  • @loicsan5616
    @loicsan5616 Рік тому +1

    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.

    • @BoualiAli
      @BoualiAli  Рік тому +3

      Happy you liked it
      I'm working on it and it will be released soon

  • @anirudh514
    @anirudh514 5 місяців тому +1

    This video is very useful, thank you very much!!

    • @BoualiAli
      @BoualiAli  3 місяці тому +1

      Glad it was helpful!

  • @user-lv5zh2ob4m
    @user-lv5zh2ob4m Рік тому +1

    Гарно освітлена тема. Дякую

  • @hamzaelbouzidi7720
    @hamzaelbouzidi7720 Місяць тому

    شكرا جزيلا على مجهودك. اتمنى ان لا تنسى المجتمع العربي من شرحك

  • @mfarooqwasi
    @mfarooqwasi 5 місяців тому

    Great Work

  • @bryanguzman4051
    @bryanguzman4051 10 місяців тому

    This is a great content, thank you so so much.

    • @BoualiAli
      @BoualiAli  10 місяців тому

      Glad you enjoyed it!

  • @johancamacho3493
    @johancamacho3493 Рік тому

    Great video ! thanks for sharing this!

  • @bartosztoropolski8191
    @bartosztoropolski8191 Рік тому +1

    i love it

  • @ashishsonune9014
    @ashishsonune9014 Рік тому

    Good concept explain by you sir 😊

  • @sserra
    @sserra Рік тому

    Thank you, I will use it for my university project. portuguese here

  • @seksky333
    @seksky333 3 місяці тому

    Really appreciated you created this tutorial for the latest Spring boot version.Right timing for me to pick up more backend skills.

    • @BoualiAli
      @BoualiAli  3 місяці тому

      Glad it was helpful!

  • @tresorkaleto1481
    @tresorkaleto1481 Рік тому +2

    you wait for JWT and aouth2 authentication together implementations.
    thank you for sharing.

  • @michaelroyf4766
    @michaelroyf4766 Рік тому +1

    thank you!

  • @konscomputertutorials7473
    @konscomputertutorials7473 10 місяців тому

    Thank you very much sir.

  • @ferio2828
    @ferio2828 7 місяців тому

    Nicely explained 👌

    • @BoualiAli
      @BoualiAli  6 місяців тому

      Glad you liked it

  • @mahamattchalle3198
    @mahamattchalle3198 Рік тому +1

    You're the Best

  • @abu-dukhan
    @abu-dukhan Рік тому +4

    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 ❤❤❤

    • @BoualiAli
      @BoualiAli  Рік тому

      Thank you, I will

    • @abu-dukhan
      @abu-dukhan Рік тому

      @@BoualiAli Thank you Sir, JazaakAllahu khairan

  • @AnvarbekTurdaliyev
    @AnvarbekTurdaliyev Рік тому

    thank you very much

  • @DR.EAM.CHASER
    @DR.EAM.CHASER Рік тому

    Great content as always :) I'm still waiting for the Swagger interation. I hope you still find time for it :)

  • @ghiles3890
    @ghiles3890 Рік тому +1

    thanks,🤗

  • @migolovach1371
    @migolovach1371 Рік тому

    ty very match from Russia

  • @erichivan5419
    @erichivan5419 Рік тому +1

    Grande ali😎

  • @sardorbekyorqulov
    @sardorbekyorqulov 5 місяців тому

    Best !

    • @BoualiAli
      @BoualiAli  3 місяці тому

      Glad you think so!

  • @shamilheydarov289
    @shamilheydarov289 7 місяців тому

    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.

  • @aziztolearn
    @aziztolearn 11 місяців тому

    👍👍👍👍

  • @Great_Sahara
    @Great_Sahara 11 місяців тому

    thank you for the great content. Can you please make a tutorial about online payement with spring boot and angular . TKU

    • @BoualiAli
      @BoualiAli  11 місяців тому +1

      aliboucoding.com/p/spring-boot-paypal-payment-integration

  • @user-xf4ht5uc1p
    @user-xf4ht5uc1p 5 місяців тому

    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…

  • @khalilbouali3480
    @khalilbouali3480 9 місяців тому

    thanks

  • @balazsvarga4216
    @balazsvarga4216 Рік тому +2

    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?

    • @BoualiAli
      @BoualiAli  Рік тому +4

      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

  • @Quasar106
    @Quasar106 7 місяців тому

    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)

    • @medAmineRg
      @medAmineRg 5 місяців тому

      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.

  • @IanCheng-bd3rm
    @IanCheng-bd3rm Рік тому

    25:20 Can add " response.setContentType("application/json"); " before " new ObjectMapper().writeValue(response.getOutputStream(), authResponse); "

  • @dagnogoyaya5639
    @dagnogoyaya5639 Рік тому +1

    Thanks for this sir ! Please do we have a course on sending email when a user creates an account🤩🙏

    • @BoualiAli
      @BoualiAli  Рік тому +1

      I have one on my website
      Aliboucoding.com/courses

  • @elyeszaabi9957
    @elyeszaabi9957 4 місяці тому

    why am i getting error 500 when the jwt goes expired ?

  • @user-jg5xy8yw6j
    @user-jg5xy8yw6j 3 місяці тому

    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?

  • @CuriousTogether
    @CuriousTogether 3 місяці тому

    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 ?

    • @BoualiAli
      @BoualiAli  2 місяці тому

      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

  • @chijiokeibekwe9710
    @chijiokeibekwe9710 11 місяців тому

    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?

    • @BoualiAli
      @BoualiAli  11 місяців тому

      first option is better

  • @ajdinpipo08
    @ajdinpipo08 Рік тому

    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!!!

    • @BoualiAli
      @BoualiAli  Рік тому +3

      I already mentioned that you can also save the refresh token and perform a second level of validation too

  • @merxxibeaucoup9093
    @merxxibeaucoup9093 Рік тому +1

    Mashallah brother … thank you !!

  • @eugenesmith9940
    @eugenesmith9940 Рік тому

    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?

    • @BoualiAli
      @BoualiAli  Рік тому

      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

  • @_5_184
    @_5_184 Рік тому

    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.

    • @BoualiAli
      @BoualiAli  Рік тому

      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

  • @DungNguyen-ki9cr
    @DungNguyen-ki9cr 5 місяців тому

    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!

    • @JayasuryaASurya
      @JayasuryaASurya Місяць тому

      I had the same doubt. Is this okay to save the refresh token in DB instead of access Token ?

  • @adhiadhil4096
    @adhiadhil4096 9 місяців тому +1

    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.

    • @medAmineRg
      @medAmineRg 5 місяців тому +1

      i guess you can set a claims inside the token (ex : token type -> refreshToken or accessToken then you can check in the backend)

  • @chungphamthanh5061
    @chungphamthanh5061 Рік тому

    I see you set the expiration time of the access token to 1 day, so why when using postman the expiration time is 60s ?

    • @BoualiAli
      @BoualiAli  Рік тому

      Just to demonstrate.
      I cannot wait one day until the token is expired to showcase it lol

  • @ridasafwan1240
    @ridasafwan1240 Рік тому

    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?

    • @BoualiAli
      @BoualiAli  Рік тому

      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

  • @user-tz2ms1cm9q
    @user-tz2ms1cm9q 6 місяців тому

    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 ?

    • @medAmineRg
      @medAmineRg 5 місяців тому

      if you use these 86400000, it will expire after 1 day

  • @emresdocumentary
    @emresdocumentary Рік тому

    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?

    • @BoualiAli
      @BoualiAli  Рік тому +1

      If you also regenerate the refresh token each time, it will never expire which is not relevant as I explained

  • @arefsa6
    @arefsa6 9 місяців тому

    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

    • @BoualiAli
      @BoualiAli  8 місяців тому

      Happy you liked it!
      Storing the token was an approach to implement logout (just an example)

  • @sonmai4840
    @sonmai4840 Рік тому

    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
      @BoualiAli  Рік тому +1

      for the refresh, you need the refresh token which hase a longer expiry period but it is not for ever (depending on you implementation)

    • @sonmai4840
      @sonmai4840 Рік тому

      @@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

  • @sehameldeen1162
    @sehameldeen1162 Рік тому +1

    I am wondering; if the jwtToken is stateless, why do we need to save it in the database?

    • @BoualiAli
      @BoualiAli  Рік тому +1

      I explained that in the logout video.
      It is just an approach (maybe not the best) to implement a logout mechanism

    • @sehameldeen1162
      @sehameldeen1162 Рік тому

      @@BoualiAli Thank you for your quick response. I understand. Do you recommend any other approach from your personal experience?

    • @goodnewsjohn2482
      @goodnewsjohn2482 7 місяців тому

      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

  • @GoncaloSilva137
    @GoncaloSilva137 Рік тому

    Hi, i dont need to store the refreshToken in the database?

    • @BoualiAli
      @BoualiAli  Рік тому

      Not necessarily in a database but you need to save it to a storage system / cache like redis

  • @johnmumo8282
    @johnmumo8282 Рік тому

    Good content i like it it really helped me...
    is it possible to combine Oauth2 with jwt in the same spring application???

    • @BoualiAli
      @BoualiAli  Рік тому

      Really happy you liked it
      Yes it is possible of course

  • @Shashee99
    @Shashee99 11 місяців тому

    when it comes to front end what is the best and secured way to store the refresh token?

    • @BoualiAli
      @BoualiAli  11 місяців тому +1

      session and local storage are perfectly fine

  • @joshmiller2954
    @joshmiller2954 11 місяців тому

    Why does your access_token expire for the demo controller after 1 minute but the application.yml is set to a day?

    • @BoualiAli
      @BoualiAli  11 місяців тому +1

      Just for the demo. It is hard to wait a day until the token expires to demonstrate

    • @joshmiller2954
      @joshmiller2954 11 місяців тому

      @@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.

  • @deepikar4404
    @deepikar4404 Рік тому

    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

    • @BoualiAli
      @BoualiAli  Рік тому

      Check if you set correctly the values. Follow the same steps as I did

    • @gucciflipflops9665
      @gucciflipflops9665 7 місяців тому

      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

    • @gucciflipflops9665
      @gucciflipflops9665 7 місяців тому

      Small typo at the end; I meant not equals null, so: if(userEmail != null)

  • @pujanshrestha5900
    @pujanshrestha5900 Рік тому

    please sir make a video for jwt exception handling

    • @BoualiAli
      @BoualiAli  Рік тому

      Already uploaded.
      Check the playlist

  • @sovannborithyun5205
    @sovannborithyun5205 11 місяців тому

    How to handle refresh token expired?

    • @BoualiAli
      @BoualiAli  11 місяців тому

      Same way as the normal token

  • @MrJayenta
    @MrJayenta Рік тому

    Plz try for the forget Password

  • @istand4myself
    @istand4myself 5 місяців тому +1

    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.

    • @gusdev-r
      @gusdev-r 2 місяці тому

      do you have some recomendation instead that guide?

  • @tami-he4mm
    @tami-he4mm 9 місяців тому

    it does not make sense,
    when you refresh token you have to refresh both tokens as well, not only access_token

    • @BoualiAli
      @BoualiAli  8 місяців тому

      really?
      So wha is it called refresh token if you have to refresh it within the real token