-
Hello, I would like to know the best way to use a Bearer token for all requests that is obtained with a login/pass: I've created a new Authenticator but i'm not sure i should mix requests inside that class... What is the best way to proceed? Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Ah you actually beat me to the documentation on this - but I would actually recommend using a custom Authenticator which is the default authenticator on your connector. Inside your connector, you should make another request to grab the token and then authenticate the request you were going to send. You’ll also need to build an if-statement to make sure you don’t run into a loop. Here is an example: <?php
use Saloon\Contracts\Authenticator;
use Saloon\Http\Auth\TokenAuthenticator;
class ForgeConnector extends Connector
{
public function resolveBaseUrl(): string
{
return 'https://forge.laravel.com/api/v1';
}
protected function defaultAuth(): ?Authenticator
{
return new ForgeAuthenticator();
}
}
//
class ForgeAuthenticator implements Authenticator
{
public function set(PendingRequest $pendingRequest): void
{
// Ignore if the request is an AuthenticateRequest to prevent loops
if ($pendingRequest->getRequest() instanceof AuthenticateRequest) {
return;
}
// Make a request to the Authentiation endpoint
$response = $pendingRequest->getConnector()->send(new AuthenticateRequest);
// Add the token to the request headers
$pendingRequest->headers()->add('Authorization', 'Bearer ' . $response->json('token'));
}
} Let me know your thoughts and if this works for you - if it does I’ll add it to the official docs |
Beta Was this translation helpful? Give feedback.
-
That's exactly that ;-) it's working correctly, amazing that in few files and lines you handle the complexity to connect to an API... Many thanks for your package and support! |
Beta Was this translation helpful? Give feedback.
That's exactly that ;-) it's working correctly, amazing that in few files and lines you handle the complexity to connect to an API...
Many thanks for your package and support!