Hi there,
Kinda of a newbie to laravel and API development. But here's the issue:
I have a route that logs a user in using Sanctum authentication like so:
public function login(Request $request){
$fields = $request->validate([
'email' => 'required',
'password' => 'required'
]);
//Check user
$user = User::where('email', $fields['email'])->first();
if(!$user || !Hash::check($fields['password'], $user->password)){
return response([
'message' => 'Bad credentials'
], 401);
}
$token = $user->createToken('userauthtoken')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response, 201);
}
In the Postman app, it works perfectly. I get a JSON object with the user information and the access token.
But when I try to make a post request using Axios in React like so:
const postData = async () => {
axios.post('/login', {
email : '[email protected]',
password : '321'
})
.then(res => console.log(res));
}
My cors.php file looks like this:
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
And in my session.php config file, the cookie domain name points to an env. field that does not exist in the env file (SESSION_DOMAIN). I found this a bit odd.
'domain' => env('SESSION_DOMAIN', null),
It returns a 419 error. Please keep in mind that this route is not protected.
From what I've read, I need to implement CSRF in my post request, but how do I go about doing this? Should I make a GET end point that returns the csrf_token() and stores it in localStorage? And then pass it somehow in the headers?
Any help is appreciated.
Thank you for reading my post