Attempting to extract the active user from a fetch request to my backend. Here is my front-end code:
let apiToken: string | null = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
fetch('http://192.168.0.6:8000/api/testURL', {
method: "POST",
//@ts-ignore
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text-plain, */*',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': apiToken
},
credentials: 'same-origin',
body: JSON.stringify(data)
})
.then(function(response): void {
console.log(response);
})
.catch(function(err): void {
console.log(err);
});
The CSRF token in a meta tag is generated from csrf_token();
Here is my backend code:
Route::post('/testURL', function(Request $request) {
$status = $request->input('status');
$comment = $request->input('comment');
$prospectType = $request->input('prospectType');
$leadId = $request->input('leadId');
$requestUser = $request->user();
return response()->json([
'status' => $status,
'comment' => $comment,
'prospectType' => $prospectType,
'leadId' => $leadId,
'user' => $requestUser
]);
});
After making the API call, the 'user' field shows as null.
Attempts with Auth::user() and Auth::id() also result in null.
Tried using Sanctum for a validation token, but applying an auth:sanctum middleware led to a 302 redirect.
(The same redirection occurs when applying 'auth' to a non-Sanctum token'd request).
Main goal amidst these challenges: Ensure user ID validation when sending the request from frontend to backend.