'Laravel Sanctum CSRF not authenticating
I have a problem understanding use of CSRF tokens with Laravel/Sanctum.
As I see, there is no need to create Sanctum API token to authenticate user, and considering that my frontend (Vue) is integrated in the Laravel resources, I want to check Auth::check()
in blade like so:
@if (auth()->check())
@php
$user_auth_data = [
'isLoggedin' => true,
'user' => Auth::user()
];
@endphp
@else
@php
$user_auth_data = [
'isLoggedin' => false
];
@endphp
@endif
I have the
<meta name="csrf-token" content="{{ csrf_token() }}">
And in every frontend request, there is a X-CSRF-TOKEN
value, but it's not authenticating.
Ofc, I'm using before login request.
.get("/sanctum/csrf-cookie")
And in API middleware I have VerifyCsrfToken.
This is how my login controller looks like:
public function login(AuthRequest $request): AuthResource
{
$auth = Auth::user();
$token = $auth->createToken('auth')->plainTextToken;
$auth->setAttribute('token', $token);
ProcessUserDevice::dispatch($auth->id, $_SERVER, $token);
return new AuthResource($auth);
}
How could I authenticate user on frontend of vue and in main blade, is it even possible?
Solution 1:[1]
CSRF is for the http requests. I mean, you will need it when you submit a from in Blade.
For API calls, you need token base authentication, which is what Sanctum provides. If you use axios to make API calls, you can use the following lines to setup it properly.
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.withCredentials = true;
I assume your Sanctum setup has no issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bulent |