You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.4 KiB

<?php
namespace authkit2\Oidc\Authentication;
use \authkit2\Oidc\Token;
/**
* Authenticates requests using an oauth token from a service account
* or user
*/
class TokenAuthentication extends Authentication
{
/**
* Token used to authenticate requests
* @var Token
*/
protected $token;
/**
* Who to call if the token is expired
* @var callable
*/
protected $refresh_callback;
/**
* Create a new token authentication provider
*
* @param Token $token token to authenticate requests with
*/
public function __construct(Token $token, callable $refreshCallback = null)
{
$this->token = $token;
$this->refresh_callback = $refreshCallback;
}
public function setRefreshCallback(callable $refreshCallback): void
{
$this->refresh_callback = $refreshCallback;
}
/**
* Authenticate the passed in request with the provided token
*
* Token authentication uses the token as a bearer token.
*
* @param \GuzzleHttp\Psr7\Request $request request to authenticate
* @return \GuzzleHttp\Psr7\Request authenticated request
*/
public function authenticate(\GuzzleHttp\Psr7\Request $request): \GuzzleHttp\Psr7\Request
{
if ($this->token->isExpired() && isset($this->refresh_callback))
{
$callback = $this->refresh_callback;
$this->token = $callback($this);
}
return $request->withHeader('Authorization', 'Bearer '.$this->token->getAccessToken());
}
}