Per-request Authentication
<?php
$api = new MusicApi();
$authResponse = $api->send(new GetAccessTokenRequest(username: 'Sam', password: 'yee-haw'));
$token = $authResponse->json()['token'];
$songsRequest = new GetSongsByArtistRequest('Luke Combs');
$songsRequest->withTokenAuth($token);
$response = $api->send($songsRequest);<?php
use Saloon\Http\PendingRequest;
use Saloon\Http\Auth\TokenAuthenticator;
class MusicApi extends Connector
{
// You should move any authentication requirements into the constructor
// of the connector so your users have to provide the authentication
// requirements before instantiating the connector.
public function __construct(
protected string $username,
protected string $password,
)
{
//
}
public function boot(PendingRequest $pendingRequest): void
{
// Let's start by returning early if the request being sent is the
// GetAccessTokenRequest. We don't want to create an infinite loop
if ($pendingRequest->getRequest() instanceof GetAccessTokenRequest) {
return;
}
// Now let's make our authentication request. Since we are in the
// context of the connector, we can just simply call $this and
// make another request!
$authResponse = $this->send(new GetAccessTokenRequest($this->username, $this->password));
// Now we'll take the token from the auth response and then pass it
// into the $pendingRequest which is the original GetSongsByArtistRequest.
$pendingRequest->authenticate(new TokenAuthenticator($authResponse->json()['token']));
}
}Last updated