Make a post request to a api that uses sanctum via Client (laravel-6.2).
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?
It looks like you're using sanctum in its SPA mode, where it ensures that all requests are stateful and that you need to first make a request to /sanctum/csrf-cookie so Laravel sets a csrf cookie that will be appended automatically in every other request (in case you're using axios, Laravel handles this).
If that is not what you're doing, you may need to configure the SESSION_DOMAIN and SANCTUM_STATEFULL_DOMAINS, go to your .env and add these, as it seems that this error does not really occur for everyone
Thanks. These things are working and already set up as you said. Just wondering how to make it via an HTTP client.It's working with get but return csrf issue with post
@nipun yes it won't work that way because the cookies[0] is false, plus sanctum is looking for X-CSRF-TOKEN header and not X-XSRF-TOKEN update your code like this and give it a try
$response2 = $client->post('http://localhost:8000/api/user/updated', [
'headers' => [
'referer' => 'http://localhost:5003',
'accept' => 'application/json',
'X-CSRF-TOKEN' => csrf_token() // the important header that causing the 419 error
]
]);
@OussamaMater
thanks. Tried this one before when you mentioned csrf_token() in a previous answer. But still Im getting the error.
also tries the below code as well. Really appreciate you help on this
@nipun the code does not make sense to me, you see, you are SETTING header to be sent with your request, and while SETTING them you're using the header() method that's used to retrieve headers, so these fields will be null most likely as you're SENDING a request and not RECEIVING one.
@nipun You are using sanctum, that's the passport docs, and the header name should be same for both Laravel 9 and Laravel 6, you should not be using header() method as it's used to retrieve data, the reference to show you an example.
@nipun Could you resolve sactum authenticating with GET request but not with POSTS? @oussamamater Traversy's video is for token genertion, not for /cookie based authentication
@marcosdipaolo well because based on the replies that's what he needed :)
And no, if you want to use cookies you can't , you need to flow the workflow set by Laravel (refer to the docs), and it's a bad idea anywhere, why would you?