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.
67 lines
1.7 KiB
67 lines
1.7 KiB
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
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
|
|
* @param ?callable $refreshCallback callback to generate us a new token when our existing one expires
|
|
*/
|
|
public function __construct(Token $token, callable $refreshCallback = null)
|
|
{
|
|
$this->token = $token;
|
|
$this->refresh_callback = $refreshCallback;
|
|
}
|
|
|
|
/**
|
|
* Set the callback to be called when the underlying token expires.
|
|
*
|
|
* @param callable $refreshCallback
|
|
* @return void
|
|
*/
|
|
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 \Psr\Http\Message\RequestInterface $request request to authenticate
|
|
* @return \Psr\Http\Message\RequestInterface authenticated request
|
|
*/
|
|
public function authenticate(\Psr\Http\Message\RequestInterface $request): \Psr\Http\Message\RequestInterface
|
|
{
|
|
if ($this->token->isExpired() && isset($this->refresh_callback))
|
|
{
|
|
$callback = $this->refresh_callback;
|
|
$this->token = $callback($this->token);
|
|
}
|
|
return $request->withHeader('Authorization', 'Bearer '.$this->token->getAccessToken());
|
|
}
|
|
}
|
|
|