'Laravel passport login CSRF token mismatch in Postman
I am learning laravel and php in general and I came upon using Laravel passport as authentication.
I followed the documentation to replace the values in various config files.
My Controller's login function:
public function login(Request $request) {
$credentials = [
'email' => $request->email,
'password' => $request->password
];
if (auth()->attempt($credentials)) {
$token = auth()->user()->createToken('test@auth')->accessToken;
return response()->json(['token' => $token], 200);
} else {
return response()->json(['error' => 'UnAuthorised'], 401);
}
}
My web routes:
Route::group(['prefix' => 'auth'], function() {
Route::post('/login', [AuthController::class, 'login'])->name('login');
Route::post('/register', [AuthController::class, 'register'])->name('register');
});
when I test login in Postman,
POST > http://127.0.0.1:8000/auth/login
Headers > Accept - application/json
Body > FormData > email([email protected]) / password(test)
Note: I created the user via tinker and I hashed the password too.
When I submit the request, it gives me error saying:
"message": "CSRF token mismatch.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
"file": "D:\\workspaces\\linneo\\treffas\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Exceptions\\Handler.php",
Solution 1:[1]
I had the same error, but it was because the URL was incorrect.
I tried to access: https://example.org/login
... instead of: https://example.org/api/login
And also ensure that you're using the right protocol. If you try to send a GET-request, but there are not routes-definitions to 'catch' the request, then you'd receive the same error.
Here is the headers that I use (that works for me):
Accept:application/json
Content-Type:application/json
Solution 2:[2]
Well I understand this frustration I have had a similar issue recently i think you can easily solve it with those two instructions
- Go to VerifyCsrfToken class or file then on protected except add URLs that are to be excepted.
Please note these are URLs that are not in the api.php routes file
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = ['/oauth/authorize','',''];
}
- On postman or API client add the following headers
Accept:application/json
Content-Type:application/json
The above worked for me ??
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 | Zeth |
| Solution 2 | Emanuel Paul Mnzava |
