我正在学习 Laravel 和 php,我偶然发现使用 Laravel Passport 作为身份验证。
我按照文档替换了各种配置文件中的值。
我的控制器的登录功能:
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);
}
}
我的网络路线:
Route::group(['prefix' => 'auth'], function() {
Route::post('/login', [AuthController::class, 'login'])->name('login');
Route::post('/register', [AuthController::class, 'register'])->name('register');
});
当我在 Postman 中测试登录时,
POST > http://127.0.0.1:8000/auth/login
Headers > Accept - application/json
Body > FormData > email([email protected]) / password(test)
注意:我通过tinker创建了用户,并且还对密码进行了哈希处理。
当我提交请求时,它给我错误消息:
"message": "CSRF token mismatch.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
"file": "D:\\workspaces\\linneo\\treffas\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Exceptions\\Handler.php",
我理解这种挫败感,我最近遇到了类似的问题,我想你可以用这两条指令轻松解决它
请注意这些 URL 不在 api.php 路由文件中
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = ['/oauth/authorize','',''];
}
Accept:application/json
Content-Type:application/json
我也遇到了同样的错误,但那是因为 URL 不正确。
我尝试访问:https://example.org/login
...而不是:https://example.org/api/login
还要确保您使用正确的协议。如果您尝试发送 GET 请求,但没有路由定义来“捕获”该请求,那么您会收到相同的错误。
这是我使用的标题(对我有用):
Accept:application/json
Content-Type:application/json