Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

EternalWay's avatar

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
0 likes
4 replies
EternalWay's avatar

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

tisuchi's avatar

@eternalway I didn't get the proper.

What is the purpose of using API with the session? The purpose of API is state less which means, you should to store any session with any user.

Ideally, every API call will provide tokens to verify who is requesting.

EternalWay's avatar

@tisuchi Unfortunately, I also don’t understand the purpose of this.

I just got stuck trying to integrate with a service that has such an API, but they don’t have tokens.

I hope I understood you correctly before answering

1 like
EternalWay's avatar

I apologize to everyone for the misunderstanding

After re-examining my code very carefully, I found out that the code was completely working and the problem was that I was passing the login parameter instead of username during authorization

Please or to participate in this conversation.