From 17d1e1db1eec6828bccd1720258144ebe3149b61 Mon Sep 17 00:00:00 2001 From: beu Date: Wed, 31 Jul 2024 11:36:15 +0200 Subject: [PATCH] add support of refresh token --- README.md | 2 +- examples/TrackManiaAuthenticator.php | 5 +++ .../TrackManiaAuthenticatorSubscriber.php | 36 +++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 examples/TrackManiaAuthenticatorSubscriber.php diff --git a/README.md b/README.md index eac3351..11f7cfb 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ php bin/console make:user Note that you have to answer **no** to the question `Does this app need to hash/check user passwords?` -Then, you could copy the files `TrackMania.php` in `src/Controller/OAuth2/` and `TrackManiaAuthenticator.php` in `src/Security/` +Then, you could copy the files `TrackMania.php` in `src/Controller/OAuth2/`, `TrackManiaAuthenticator.php` in `src/Security/` and `TrackManiaAuthenticatorSubscriber.php` in `src/Event/`. Then change the `config/packages/knpu_oauth2_client.yaml` file like this: diff --git a/examples/TrackManiaAuthenticator.php b/examples/TrackManiaAuthenticator.php index 0f091e2..cc1e56f 100644 --- a/examples/TrackManiaAuthenticator.php +++ b/examples/TrackManiaAuthenticator.php @@ -42,6 +42,11 @@ class TrackManiaAuthenticator extends OAuth2Authenticator $client = $this->clientRegistry->getClient('TrackMania'); $accessToken = $this->fetchAccessToken($client); + // Store the refresh token in the session + if ($accessToken->getRefreshToken() !== null) { + $request->getSession()->set('oauth2_trackmania_accesstoken', $accessToken); + } + $selfvalidating = new SelfValidatingPassport( new UserBadge($accessToken->getToken(), function() use ($accessToken, $client) { /** @var Beu\TrackMania\OAuth2\Client\Provider\TrackManiaProviderOwner $user */ diff --git a/examples/TrackManiaAuthenticatorSubscriber.php b/examples/TrackManiaAuthenticatorSubscriber.php new file mode 100644 index 0000000..23bf73c --- /dev/null +++ b/examples/TrackManiaAuthenticatorSubscriber.php @@ -0,0 +1,36 @@ +getRequest()->getSession()->get('oauth2_trackmania_accesstoken'); + + if ($accessToken !== null && $accessToken->hasExpired()) { + $client = $this->clientRegistry->getClient('TrackMania'); + $accessToken = $client->refreshAccessToken($accessToken->getRefreshToken()); + + // Store the refresh token in the session + if ($accessToken->getRefreshToken() !== null) { + $event->getRequest()->getSession()->set('oauth2_trackmania_accesstoken', $accessToken); + } + } + } + + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::CONTROLLER => 'onKernelController', + ]; + } +} \ No newline at end of file