openiddict / openiddict-core

Flexible and versatile OAuth 2.0/OpenID Connect stack for .NET
https://openiddict.com/
Apache License 2.0
4.47k stars 527 forks source link

Dantooine (BFF) - Checking Access Token Expiration #2157

Closed realisable closed 3 months ago

realisable commented 3 months ago

Confirm you've already contributed to this project or that you sponsor it

Version

5.7.0

Question

In the Dantooine server example, there is a comment which reads 'In a real world application, the expiration date of the access token should be checked before sending a request to avoid getting a 401 response. Once expired, a new access token could be retrieved using the OAuth 2.0 refresh token grant (which could be done transparently).'

Do you have an example or some guidance of how to do this? (At this point in the request we only have 3 claims on the HttpContext.User object).

Many Thanks

kevinchalet commented 3 months ago

Hey @realisable,

Thanks a lot for sponsoring the project! ❤️

Do you have an example or some guidance of how to do this? (At this point in the request we only have 3 claims on the HttpContext.User object).

I updated the Dantooine sample to use a custom DelegatingHandler that detects whether an existing access token is about to expire and automatically refresh tokens via OpenIddictClientService.AuthenticateWithRefreshTokenAsync() when the token is known to be expired or when a 401 response was returned by the authorization server. It also now includes code to return a refreshed authentication cookie containing the new tokens when a grant_type=refresh_token request was sent: https://github.com/openiddict/openiddict-samples/pull/332.

Hope you'll find it useful 😃

Cheers.

realisable commented 3 months ago

Kevin, thank you. That is awesome!