-
Hi there and thanks for the great package! I am using Laravel and have the following auth process for an api I am using:
I want to be able to use the api with the connector as followed: $connector = new ApiConnector($client, $clientSecret, $username, $password);
$connector->send(new GetSomeItemsRequest()) But it should cache the auth token and only perform an new auth request whenever the token is about to expire. Furthermore I want to be able to use the "recording Responses" testing feature for the auth method as well. I thought about using a |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hey @Sparclex really sorry about missing this! I've had situations where I've had to do the same thing. The best solution I've found so far is using Saloon's boot method on the connector to make another request before the real request gets sent. Additionally, you could clean up this logic into an invokable middleware class and use that middleware in here too. public function boot(PendingRequest $pendingRequest)
{
// Let's first return early if the connector is about to make the same request.
// we don't want an infinite loop on our hands!
if ($pendingRequest->getRequest() instanceof AuthenticationRequest) {
return;
}
// Check if we already have valid authentication before. You might check your user's table?
// Quick time check
if ($user->api_expiry_at > $now) {
$pendingRequest->withTokenAuth($user->api_token);
return;
}
// Otherwise, we'll make a request to authenticate. All the credentials should be passed into the connector or app globals.
$authenticationResponse = $this->send(new AuthenticationRequest($clientId, $clientSecret, $username, $password));
$token = $authenticationResponse->json()['token']; // Get the token (may be different)
// Authenticate the original PendingRequest
$pendingRequest->withTokenAuth($user->api_token);
// Now save it on the user
$user->api_token = $token;
$user->api_expiry_at = $now;
$user->save();
// Original request is sent
} |
Beta Was this translation helpful? Give feedback.
Hey @Sparclex really sorry about missing this!
I've had situations where I've had to do the same thing. The best solution I've found so far is using Saloon's boot method on the connector to make another request before the real request gets sent. Additionally, you could clean up this logic into an invokable middleware class and use that middleware in here too.