saloonphp / saloon

🤠 Build beautiful API integrations and SDKs with Saloon
https://docs.saloon.dev
MIT License
2.03k stars 105 forks source link

Refresh token with Client Credentials Grant #372

Closed asamofal closed 6 months ago

asamofal commented 6 months ago

Hi! I noticed that Refreshing Access Tokens section is missing in the Client Credentials Grant docs section, and refreshAccessToken method is missing in ClientCredentialsGrant trait, the refresh token doesn't go to AccessTokenAuthenticator even. Could you please explain why this is the case?

image

I'm currently working on integrating with this API, and it appears that I'll need to refresh the tokens. Could you guide how to proceed with this?

Sammyjo20 commented 6 months ago

Hey @asamofal

This is not something I originally anticipated when building the client credential support but looking at the RFC 6749 spec it does look like "Issuing a refresh token is optional at the discretion of the authorization server.".

I would recommend writing a function on your connector to manually refresh this access token and build a separate request for it. I'll also take a note to add this to v4 when I start working on it.

asamofal commented 6 months ago

@Sammyjo20 Okay, good to know 👍 Probably shouldn't be too hard in implementation, looks pretty similar to what we already have in AuthorizationCodeGrant...

Sammyjo20 commented 6 months ago

You should be able to achieve it by extending the following methods:

and then implement a refresh token request.

Sammyjo20 commented 6 months ago

I'm going to close the issue - but please let me know if you have any questions.

asamofal commented 6 months ago

This is my workaround for anyone who will face the same issue as me. Will be glad if one of the new Saloon versions supports it out of the box.

class MyConnector extends Connector
{
    use ClientCredentialsGrant;
    use AcceptsJson;

    private function __construct(
        private readonly string $clientKey,
    ) {
        $authenticator = $this->getAccessToken();
        $this->authenticate($authenticator);
    }

    public function resolveBaseUrl(): string
    {
        return '';
    }

    protected function defaultOauthConfig(): OAuthConfig
    {
        return OAuthConfig::make()
            ->setClientId('')
            ->setClientSecret('')
            ->setAuthorizeEndpoint('authorize')
            ->setTokenEndpoint('/oauth/token');
    }

    /**
     * @throws JsonException
     */
    protected function createOAuthAuthenticatorFromResponse(Response $response): OAuthAuthenticator
    {
        $responseData = $response->object();

        $accessToken = $responseData->access_token;

        $expiresAt = null;
        if (isset($responseData->expires_in) && is_numeric($responseData->expires_in)) {
            $expiresAt = (new DateTimeImmutable())->add(
                DateInterval::createFromDateString((int) $responseData->expires_in . ' seconds')
            );
        }

        $refreshToken = $responseData->refresh_token ?: null;

        return new AccessTokenAuthenticator($accessToken, $refreshToken, $expiresAt);
    }

    /**
     * @throws FatalRequestException
     * @throws RequestException
     * @throws JsonException
     */
    public function send(Request $request, MockClient $mockClient = null, callable $handleRetry = null): Response
    {
        if ($this->authenticator?->hasExpired()) {
            $refreshTokenResponse = parent::send(
                new GetRefreshTokenRequest(
                    $this->oauthConfig,
                    $this->authenticator->getRefreshToken()
                )
            );
            $authenticator = $this->createOAuthAuthenticatorFromResponse($refreshTokenResponse);
            $this->authenticate($authenticator);
        }

        return parent::send($request, $mockClient, $handleRetry);
    }
}

@Sammyjo20 I even think I can prepare a PR for this for v3 (this should not break anything) but I'm missing one piece - what calls refreshAccessToken method from AuthorizationCodeGrant?