laravel 7 sanctum Hash::check 总是返回 false
Posted
技术标签:
【中文标题】laravel 7 sanctum Hash::check 总是返回 false【英文标题】:laravel 7 sanctum Hash::check always returns false 【发布时间】:2021-06-05 03:59:57 【问题描述】:我正在尝试使用 sanctum 构建 laravel auth api,我按照文档进行操作,但收到此错误:
"message": "The given data was invalid.",
"errors":
"data": [
"The provided credentials are incorrect."
]
这是控制器:
public function login(Request $request)
$request->validate([
'email' => 'required',
'password' => 'required',
'device_name' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password))
throw ValidationException::withMessages([
'data' => ['The provided credentials are incorrect.'],
]);
$token = $user->createToken($request->device_name)->plainTextToken;
$response = [
'user' => $user,
'token' => $token,
];
return response($response, 201);
return $user->createToken($request->device_name)->plainTextToken;
我找到了这个解决方案,但即使密码错误,它也会返回“true”:
Laravel Hash::check() always return false
【问题讨论】:
【参考方案1】:尝试这种方式,使用attempt
$request->validate([
'email' => 'required|email|string',
'password' => 'required|string',
'device_name' => 'required',
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$token = $user->createToken($request->device_name)->plainTextToken;
//return....
【讨论】:
以上是关于laravel 7 sanctum Hash::check 总是返回 false的主要内容,如果未能解决你的问题,请参考以下文章
带有 Vuejs 的 Laravel 7.x Sanctum (SPA) 总是返回 401 Unauthorized
安装 sanctum 时 Laravel Composer 错误:与合同冲突
为啥我的 CSRF 令牌与 Laravel 和 Sanctum 不匹配?
Laravel Sanctum 无法使用 Postman 登录