有没有办法在laravel jwt-auth中使用用户名(或任何自定义列)进行身份验证,而不是电子邮件?
这是现有代码
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
try {
// verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token'], 500);
}
// if no errors are encountered we can return a JWT
return response()->json(compact('token'));
}
我想做这样的事情
$credentials = $request->only('username', 'password');
一种方法是将用户名放在电子邮件列中,但这是一个糟糕的解决方案。
答案 0 :(得分:2)
Looking around,看起来可以通过设置$credentials = $request->only('username', 'password');
等凭据来实现此目的。
所以一切都会是这样的:
public function authenticate(Request $request)
{
// grab credentials from the request
//$credentials = $request->only('email', 'password');
// Change email to username
$credentials = $request->only('username', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
答案 1 :(得分:1)
我找到了方法here
我们可以从模型中获取用户(在自定义字段的基础上),例如
//抓住一些用户
$user = User::first();
并手动验证。
$token = JWTAuth::fromUser($user);
答案 2 :(得分:0)
//Use case for login with email or username
public function login(Request $request){
// Request input contains username, email and password
if ($request->has(['username', 'email', 'password'])) {
$credentials = $request->only('email', 'password');
} // Request input contains `enter code here`username and password
elseif ($request->has(['username', 'password'])) {
$credentials = $request->only('username', 'password');
} // Request input contains email and password
elseif ($request->has(['email', 'password'])) {
$credentials = $request->only('email', 'password');
}
else {
$credentials = $request->only('email', 'password');
}
try {
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(['invalid_email_or_password']);
}
} catch (JWTAuthException $e) {
return response()->json(['failed_to_create_token'], 500);
}
return response()->json(compact('token'));
}