Make a post request to a api that uses sanctum via Client (Laravel-6.2)

1.1k Views Asked by At

I have 5 applications that use the same sanctum API for authentication. What I really want to do is to make a POST request sanctum API from another application. I do GET requests like the below and it's working. But when I make a POST request it returns csrf token mismatch error.

So could someone please tell me is it possible to make a post request into a sanctum API via Client?

            $response = $client->get('http://localhost:8000/api/user', [
                'headers' => [
                    'accept' => 'application/json',
                    'cookie' => $request->header('cookie'),
                    'referer' => $request->header('referer'),
                ]
            ]);

Thanks

2

There are 2 best solutions below

1
AudioBubble On

i use Bearer instead of cookie , in sanctum laravel reads access tokens from Authorization in header.

this is how i make request from laravel client to sanctum (an example of my code):

 $response = Http::withHeaders([
        "Accept"=> "application/json",
        "Authorization" => "Bearer " . Cookie::get("Laravel")
    ])
    ->post("http://localhost:8088/api/v1/url/find", ["find" => $request->find]);

i send my headers with method withHeaders as an associative array and send my post body with post method second argument.

read more here : https://laravel.com/docs/9.x/http-client

0
mdougllas On

You're missing some headers on your requests. You need to first make a request to "/sanctum/csrf-cookie", what gives you a CSRF token. Then you pass that token as the value for the header "X-CSRF-TOKEN". Sanctum documentation explains it very well. https://laravel.com/docs/8.x/sanctum#spa-authenticating Wish you luck!