Skip to content

Using refresh token grant type for 2-legged OAuth #14

@bogdanghervan

Description

@bogdanghervan

We are trying to make the middleware work with a 2-legged OAuth flow. The server we are connecting to has already authorized our app, and we've been issued a refresh token (which doesn't seem to expire) that we can use to get new access tokens.

However, there's probably something I'm missing or the middleware is not quite designed for this.

I've made it work in the end, but perhaps there's a better way?

Here's my code:

$config = [
    'client_id' => 'ABC',
    'client_secret' => 'DEF',
    'refresh_token' => 'GHI'
];

$clientCredentialsGrantType = new ClientCredentials($refreshClient, $config);
$refreshTokenGrantType = new RefreshToken($refreshClient, $config);
            
$oauth = new OAuth2Middleware($clientCredentialsGrantType, $refreshTokenGrantType);
$oauth->setAccessToken([
    'refresh_token' => $config['refresh_token'],
    'expires_in' => -1
]);

Here I'm tricking the middleware it has acquired an access token which has expired, so that these conditions are met:

  • Inside OAuth2Handler::requestNewAccessToken I'm learning that a raw token must exist:
if ($this->refreshTokenGrantType && $this->rawToken && $this->rawToken->getRefreshToken()) {
  • Next in OAuth2Handler::getAccessToken:
if ($this->rawToken === null || $this->rawToken->isExpired()) {

For the expiration check to be evaluated to true, I'm setting the expiration to a date in the past via expires_in - it can't be the default 0, since isExpired won't allow it:

public function isExpired()
{
    return $this->expiresAt && $this->expiresAt < time();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions