Master Refresh Tokens in ASP.NET Core (building from scratch)

  Рет қаралды 8,652

Milan Jovanović

Milan Jovanović

Күн бұрын

Пікірлер: 84
@MilanJovanovicTech
@MilanJovanovicTech Күн бұрын
Want to master Clean Architecture? Go here: bit.ly/3PupkOJ Want to unlock Modular Monoliths? Go here: bit.ly/3SXlzSt
@dkroderos
@dkroderos 5 күн бұрын
Bonus tip: the refresh token can be returned to the user by storing it in an HTTP-only cookie with the SameSite attribute set to Strict. This ensures that no JavaScript code can access the refresh token, which helps protect users from XSS attacks. The client app would call the refresh endpoint without needing the refresh token in the body, as the token is already stored in the cookie. However, implementing this requires the API and frontend to be on the same domain. To achieve this, I use a reverse proxy to map the frontend web app to the root (/) and the API to /api/. I'm still a student, so please feel free to correct me if I'm wrong (〃 ̄ω ̄〃).
@MilanJovanovicTech
@MilanJovanovicTech 5 күн бұрын
Quality tip!
@o0Qu
@o0Qu 5 күн бұрын
This is absolutely the correct way to do it, theres no reason to return the refreshToken to the client in a response, besides the refresh logic should only be execute on new login and statuscode 401, or on a browser refresh.
@mahmoudalaskalany
@mahmoudalaskalany 5 күн бұрын
That is true and that is how Identity server 4 is doing it with oidc-client library that is used in frontend apps but as you said frontend and backend must be on same domain to avoid third party cookie policy
@antonmartyniuk
@antonmartyniuk 5 күн бұрын
Almost no one created a video on how to build refresh tokens. Finally the video we needed!
@MilanJovanovicTech
@MilanJovanovicTech 5 күн бұрын
Yep, no rocket science here. Wonder why that is?
@antonmartyniuk
@antonmartyniuk 5 күн бұрын
@MilanJovanovicTech explain me
@elkprostoelk
@elkprostoelk 5 күн бұрын
Milan, you are my savior! I searched for a GOOD refresh token tutorial just a week ago, and you have finally done it! Thanks!
@MilanJovanovicTech
@MilanJovanovicTech 4 күн бұрын
You're welcome!
@RMarjanovic
@RMarjanovic 5 күн бұрын
Love it! Actually implementing this right now. So this was right on time. Buy yourself a sljivovica 😂🎉
@MilanJovanovicTech
@MilanJovanovicTech 5 күн бұрын
Happy to be of service! 😁
@dotnetMasterCSharp
@dotnetMasterCSharp 2 күн бұрын
Awesome and useful content thank you Milan!
@MilanJovanovicTech
@MilanJovanovicTech 2 күн бұрын
You're welcome!
@arcadiobastidas9707
@arcadiobastidas9707 5 күн бұрын
Best real world scenarios .Net channel!
@MilanJovanovicTech
@MilanJovanovicTech 5 күн бұрын
Much appreciated!
@Jabroni24601
@Jabroni24601 5 күн бұрын
Would love to see the UI flow of refresh tokens. Say I click Save on a page, call the Api, but my jwt has expired and I get the 401 back from the Api, what would the flow be on the UI side so it appears no different to the end user that a new jwt/refresh token had to be generated before calling the Api again trying to do the save
@kyreehenry9202
@kyreehenry9202 5 күн бұрын
It's easier with mobile development and client side frontend development frameworks.. other than you'll make use of Polly and also very importantly implement locking
@MilanJovanovicTech
@MilanJovanovicTech 5 күн бұрын
Catch error - > Check if 401 ? Yes - > Send request with refresh token - > Get new access token and retry request Another approach is pre-fetching the access token if it's about to expire
@Arda_Atik
@Arda_Atik 3 күн бұрын
Can you show how "Catch error - > Check if 401 ? Yes - > Send request with refresh token - > Get new access token and retry request" could be implemented I have seen it done with DelegateHandlers but I didn't get it
@alexandrehando
@alexandrehando 3 күн бұрын
Great video! How we can manage to logout or force the unauthorized to the current bearer token that has not expired yet within the 10 minutes?
@MilanJovanovicTech
@MilanJovanovicTech 3 күн бұрын
Need some way to send message to the client (websocket?) and tell it to log out
@alibabapour7418
@alibabapour7418 5 күн бұрын
Why not using Keyclock or other alternatives ?
@MilanJovanovicTech
@MilanJovanovicTech 4 күн бұрын
Check my other videos
@alibabapour7418
@alibabapour7418 4 күн бұрын
@MilanJovanovicTech already watched it, I became a fan of Keyclock because of you
@alibabapour7418
@alibabapour7418 4 күн бұрын
@MilanJovanovicTech already watched it I became a fan of Keyclock because of you
@mottahh4162
@mottahh4162 Күн бұрын
As all jwt have their expiry in them, why not check for expiry instead of waiting for the 401?
@MilanJovanovicTech
@MilanJovanovicTech 22 сағат бұрын
Sure, you can check the expiry and refresh the token.
@shadowsir
@shadowsir 3 күн бұрын
We did almost exactly the same thing EXCEPT, we use a secure httponly cookie to store the refresh tomen AND we rotate the refresh token (delete the old one and issue a new one) every time a new access token is requested. Why a secure httponly cookie? So it can't be retrieved via javascript using a malicious script.
@MilanJovanovicTech
@MilanJovanovicTech 3 күн бұрын
Nice!
@vbachris
@vbachris 5 күн бұрын
curious, instead of storing the tokens in db, couldn't you just validate the jwt signature against a private certificate?
@vbachris
@vbachris 5 күн бұрын
because you can't cancel them if needed
@MilanJovanovicTech
@MilanJovanovicTech 3 күн бұрын
How would that help us?
@varunp3620
@varunp3620 2 күн бұрын
can you send git url for this project please ?
@MilanJovanovicTech
@MilanJovanovicTech 22 сағат бұрын
www.patreon.com/milanjovanovic
@bogdanb904
@bogdanb904 5 күн бұрын
Why not use a guid for the token value?
@MilanJovanovicTech
@MilanJovanovicTech 4 күн бұрын
Feel free to use whatever
@callegarip
@callegarip 3 күн бұрын
I ran into a problem where every time I deploy the backend code, my users get signed out from the client. Is this expected? I thought as long as te token is still valid then you should continue being logged in.
@MilanJovanovicTech
@MilanJovanovicTech 2 күн бұрын
Yes, that is quite strange. What's the client application?
@callegarip
@callegarip 2 күн бұрын
@@MilanJovanovicTechthis is a react app in the frontend and net core api in the backend.
@MarvinKleinMusic
@MarvinKleinMusic 3 күн бұрын
Thanks for this video! Could you also show us how we should consume this kind of authentification in a Blazor environment? :)
@MilanJovanovicTech
@MilanJovanovicTech 3 күн бұрын
1) Send HTTP request 2) Handle 401 response - > Check if refresh token exists - > Send refresh token request and get new access token 3) Repeat 1)
@MarvinKleinMusic
@MarvinKleinMusic 3 күн бұрын
@ yea I don‘t get how I can do step 2 here. How and where should I save the access/refresh token? And how do I use it to authorize my Blazor app and append it to each request which comes from it. I could save both tokens in localStorage but since those can easily be read wouldn‘t it just make more sense to just expand the expire date of the access token? I would be really thankful if you could help me out here. I‘m struggling with this since .NET 3.1
@Arda_Atik
@Arda_Atik 4 күн бұрын
How would this work in a webapp in that the user isn't calling refreshToken manually so how do you intercept the request if the accessToken is expired you'd need to replace it with a new one
@MilanJovanovicTech
@MilanJovanovicTech 3 күн бұрын
You can intercept the token validation flow and refresh it
@Arda_Atik
@Arda_Atik 3 күн бұрын
@@MilanJovanovicTech I'd love it if you could give me a source for that I have seen people do it using DelegateHandlers but I didn't really get it
@Arda_Atik
@Arda_Atik 3 күн бұрын
@@MilanJovanovicTech Yeah I have seen it done using DelegateHandlers but I didn't really get it can you give me a source if you have one
@Frustrated-Tax-Payer
@Frustrated-Tax-Payer 4 күн бұрын
I implement the refresh token exactly like this in my APIs.
@MilanJovanovicTech
@MilanJovanovicTech 3 күн бұрын
Nice
@letsgodancin7906
@letsgodancin7906 2 күн бұрын
Have you considered using redis to cache the refresh token instead of storing them inside the database? Also, love your content, keep it up.
@MilanJovanovicTech
@MilanJovanovicTech 2 күн бұрын
The lifetime of these tokens is long (days, months). Would we want long-lived data to stay in Redis?
@antonmartyniuk
@antonmartyniuk 3 күн бұрын
How do you delete old used refresh tokens? Ideally it should be deleted when creating a new token paid for the user, so no one could use the old refresh token to get a new one. Video suggestion: show how to implement dynamic update of user claims using refresh tokens without forcing a user to re-login
@MilanJovanovicTech
@MilanJovanovicTech 2 күн бұрын
A background job can clean them up.
@mateuszsarnowski5570
@mateuszsarnowski5570 4 күн бұрын
Hi Milan! Thanks for the video-I really appreciate your work. However, regarding the refresh token implementation, I believe you’re missing a verification step to check for expired refresh tokens. This would ensure that the user has previously authenticated with their valid password. Additionally, the approach you demonstrated for cleaning the refresh token table could create issues when a user is logged in from multiple devices (for example, both a PC and a smartphone).
@MilanJovanovicTech
@MilanJovanovicTech 4 күн бұрын
Expiration covered around 9:55 - is it not? The latter concern is valid, and can be solved using some sort of device ID. But then again, this could also be a business decision. Would we want to force re-logging on all devices?
@mateuszsarnowski5570
@mateuszsarnowski5570 15 сағат бұрын
What I mean is that if we verify the refresh token while skipping the access token, it might result in a situation where the user, by providing only the refresh token, obtains an access token. We should do it in such a way that we verify if the access token, despite its expiration date, is valid, extract the user ID from it, and if the user with that user ID is found in the database, then we verify their refresh token.
@I_Am_Dani
@I_Am_Dani 4 күн бұрын
Can you make a video about HierarchyId and how to use it DDD
@MilanJovanovicTech
@MilanJovanovicTech 3 күн бұрын
What is HierarchyId?
@FarukLuki111
@FarukLuki111 5 күн бұрын
So I give the caller a very „timely limited“ accessToken (due to security reasons) but also gib him a „longer valid“ refreshToken the caller can use to create new tokens all the time😂 So if I „fear“ that the access token might get stolen (due to bad implementation of the caller/client) it does not increase security at all introducing a refresh token! Right?! OR probably I just did not get it! Another thing: it ist not a good pattern/style to create the primary key of a table (in your case the guid) in the code to set it than as the primary key of that row! This should be done by the (for example) SQL server! Because the database designs its indexes (eg primairy keys) with a tree and map and keeps therefore the guids „similar“! Generating own primary key guids breaks that and decreases performance!!
@MilanJovanovicTech
@MilanJovanovicTech 4 күн бұрын
| OR probably I just did not get it! Yep. Refresh tokens are easily revocable. Just delete them from the DB and the client is forced to login again.
@gustavonavarro8484
@gustavonavarro8484 4 күн бұрын
Could you please put the black friday discount back on the courses? I couldn't buy it because they hadn't paid me and now it's too late.
@MilanJovanovicTech
@MilanJovanovicTech 4 күн бұрын
@@gustavonavarro8484 Send me an email, I got you
@kyreehenry9202
@kyreehenry9202 5 күн бұрын
Hi @Milan
@MilanJovanovicTech
@MilanJovanovicTech 5 күн бұрын
Hey
@nouchance
@nouchance 5 күн бұрын
AWESOME!
@MilanJovanovicTech
@MilanJovanovicTech 5 күн бұрын
Thanks!
@AmateurSpecialist
@AmateurSpecialist 5 күн бұрын
Let's just take a moment to appreciate that he has his IDE configured to treat unused arguments as errors. Talk about YAGNI.
@MilanJovanovicTech
@MilanJovanovicTech 5 күн бұрын
That's what you notice from the entire video? 😂 It's actually all warnings. TreatWarningsAsErrors=True. Useful stuff. Prevents dead code from staying in your codbase.
@itirush2701
@itirush2701 Күн бұрын
Day 50 How i am waiting Milian make your implementation OAuth2 without library ._.
@MilanJovanovicTech
@MilanJovanovicTech 22 сағат бұрын
Which OAuth2 lib?
@sunzhang-d9v
@sunzhang-d9v 4 күн бұрын
"Multiple logins, multiple access tokens, how to invalidate the previous access tokens?"
@MilanJovanovicTech
@MilanJovanovicTech 4 күн бұрын
You're talking about logging the user out of all other sessions?
@sunzhang-d9v
@sunzhang-d9v 4 күн бұрын
@@MilanJovanovicTech yes
@user-dc9zo7ek5j
@user-dc9zo7ek5j 5 күн бұрын
I want to mention, there is no point of doing this if you are the authority and the user of the access token, other than to have revoking functionality. It is much simpler to create an access token that has 90 days of validity and let the user reauthenticate. Just having refresh token does not improve security by any means, and has no real security benefits if they are created and used at the same source.
@MaxwellHay
@MaxwellHay 5 күн бұрын
This is not true. For OAuth/OIDC, short lived token is always recommended because of the nature of the validation. This is the one of the key resolutions for cookie stealing and user sign out but token is still valid.
@MaxwellHay
@MaxwellHay 5 күн бұрын
I don’t want to people to get confused but who is the authority is not the key here but the way of the validation. I like the video but it’s really important to follow the industry standards like OAuth/OIDC especially for security.
@kyreehenry9202
@kyreehenry9202 5 күн бұрын
So many things you can achieve with refresh tokens, example * revalidating the IP address and notify the user of account access from a different location. * revalidating the userAgent and logout the user when the refresh token is carried out from a different device. The list goes on....
@MaxwellHay
@MaxwellHay 5 күн бұрын
@@kyreehenry9202 your examples are not specific for refresh token though. You can customize the validation logic with access token as well. One of the key feature of OIDC jwt access/id token is its self contained so that validation process can be done really fast. More time consuming validations can be done in like token refresh.
@user-dc9zo7ek5j
@user-dc9zo7ek5j 5 күн бұрын
@@kyreehenry9202 The list stops here :) Validating the IP is a really bad user experience, I can switch from mobile network to WIFI, to wire and still be on the same account. The UserAgent in 90% of the cases is chrome. There are global services like youtube, google, twitter that are using OAuth2 and are still getting compromised even with the tokens and much more sophisticated security practices. You really cannot protect an external device like the user's from bad actors. Please give me a valid reason other than revoking functionality and reducing the load on the auth and user services. In the video present is the same entity and there are no real benefits.
The Right Way To Build Async APIs in ASP.NET Core
20:12
Milan Jovanović
Рет қаралды 11 М.
Session Vs JWT: The Differences You May Not Know!
7:00
ByteByteGo
Рет қаралды 280 М.
Creative Justice at the Checkout: Bananas and Eggs Showdown #shorts
00:18
Fabiosa Best Lifehacks
Рет қаралды 35 МЛН
А я думаю что за звук такой знакомый? 😂😂😂
00:15
Денис Кукояка
Рет қаралды 6 МЛН
黑天使只对C罗有感觉#short #angel #clown
00:39
Super Beauty team
Рет қаралды 31 МЛН
Implementing the Transactional Outbox Pattern from Scratch
24:27
Milan Jovanović
Рет қаралды 11 М.
CQRS Doesn't Have To Be Complicated | Clean Architecture, .NET 6
24:09
Milan Jovanović
Рет қаралды 116 М.
Your REST API Errors Are Wrong. Problem Details Will Fix This
16:14
Milan Jovanović
Рет қаралды 10 М.
Microservices with Databases can be challenging...
20:52
Software Developer Diaries
Рет қаралды 106 М.
This Video is AI Generated! SORA Review
16:41
Marques Brownlee
Рет қаралды 2,8 МЛН
7 Design Patterns EVERY Developer Should Know
23:09
ForrestKnight
Рет қаралды 75 М.
Implementing JWT Authentication in ASP.NET Core
23:51
Nick Chapsas
Рет қаралды 44 М.
Finally.... But it's exciting!
13:58
Maximilian Schwarzmüller
Рет қаралды 25 М.