我正在使用jwt-auth for auth API with laravel并编写以下代码。
我的注册API工作正常,我的登录API返回invalid_credentials
错误。
为什么呢?
laravel版本:5.4
public function login(Request $request) {
$credentials = $request->only('username', 'password');
try {
$token = JWTAuth::attempt($credentials);
if (!$token) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 400);
}
return response()->json(compact('token'), 200);
}
public function register(Request $request) {
$credentials = $request->only('email', 'username', 'password', 'name');
$validator = Validator::make($credentials, [
'name' => 'required|max:80',
'username' => 'required|max:80|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6',
]);
if ($validator->fails()) {
$errors = $validator->errors();
return response()->json(['error' => array(
'name' => $errors->first('name'),
'email' => $errors->first('email'),
'username' => $errors->first('username'),
'password' => bcrypt('password'),
)], 400);
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'username' => $request->username,
'password' => $request->password,
]);
$token = JWTAuth::fromUser($user);
return response()->json(compact('token'));
}
答案 0 :(得分:1)
使用email
代替username
。 Laravel也使用了列email
和JWTAuth。
$credentials = $request->only('email', 'password');
要将更改用户名列设为username
,您需要更改控制器中的username
内部功能。
答案 1 :(得分:1)
我尝试任何解决方案而不工作,再次检查我的代码并在我的代码中发现错误。我在验证中做bcrypt而在用户创建时没有任何内容。纠正了这一点,它对我有用。
public function login(Request $request) {
$credentials = $request->only('username', 'password');
try {
$token = JWTAuth::attempt($credentials);
if (!$token) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 400);
}
return response()->json(compact('token'), 200);
}
public function register(Request $request) {
$credentials = $request->only('email', 'username', 'password', 'name');
$validator = Validator::make($credentials, [
'name' => 'required|max:80',
'username' => 'required|max:80|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6',
]);
if ($validator->fails()) {
$errors = $validator->errors();
return response()->json(['error' => array(
'name' => $errors->first('name'),
'email' => $errors->first('email'),
'username' => $errors->first('username'),
'password' => $errors->first('password'),
)], 400);
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'username' => $request->username,
'password' => bcrypt($request->password),
]);
$token = JWTAuth::fromUser($user);
return response()->json(compact('token'));
}
答案 2 :(得分:0)
在我的情况下,此错误是由于表中重复的电子邮件:(