I’ve been struggling with this for quite some time, but alas, I haven’t had to work with an API that runs on cookies before
Jun 4, 2024
4
Level 1
Cookie auth api
How to send requests from the server to the API of another service if authorization is through cookies?
My goal is to log in to the API of a third-party service through my server, but every time I get a message that the session_expired
public function __construct(string $login, string $password)
{
$this->client = Http::baseUrl('another_api_link');
$this->login = $login;
$this->password = $password;
if (!Cache::has($login)) {
$requestCookies = $this->auth($login, $password)->cookies();
Cache::put($login, $requestCookies, 3000);
}
}
public function auth($login, $password): Response
{
return $this
->client
->asForm()
->post(
'/',
[
'login' => $login,
'password' => $password,
]
);
}
public function yesterdayBookings()
{
$yesterday = date('Y-m-d', strtotime('-1 day'));
return $this
->client
->withHeaders([
'X-Requested-With' => 'XMLHttpRequest',
])
->withOptions(['cookies' => Cache::get($this->login)])
->post(
'/planning/bookings',
[
'dfrom' => $yesterday,
'dto' => $yesterday,
'daily' => 1,
]
);
}
Next, I try to do the following via Tinker:
$class = new Namespace\MyClass($login, $password);
$response = $class->yesterdayBookings();
$response->body()
Output:
session_expired
Please or to participate in this conversation.