I want to use user_password
instead of just password
for the name of the password column for the database of my API. So here is the code of the login()
method to retrieve the token in my PassportController
:
public function login() {
if (Auth::attempt(['user_login' => request('login'), 'password' => request('user_password')])) {
$user = Auth::user();
$success['token'] = $user->createToken('ToutelaBreizh')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
} else {
return response()->json(['error' => 'Unauthorised.'], 401);
}
}
The parameters of the request to this controller are login
and password
.
The problem is when I go to the route associated to this controller, let's say POST /api/login
. I get this error:
ErrorException: Undefined index: password in file ... EloquentUserProvider.php on line 133
[First lines of the stack trace...]
- ... PassportController.php:21
The 21st line in my PassportController is the second line of the login function I posted above and indeed, the password
field is not informed in the credentials I wrote: I wrote user_password
instead of password
, but the string password
is hard coded in the EloquentUserProvider.php, line 133:
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
As suggested by this answer, I tried to override the validateForPassportPasswordGrant($password)
in the User.php
model but it didn't help:
public function validateForPassportPasswordGrant($password)
{
return Hash::check($password, $this->user_password);
}
How should I do to have user_password
in my database and not password
?
Thank you for your help.
That issue is actually not specific to Passport, it has more to do with the Auth Guard behavior, which is abstracted from Passport. Simply add this to your user Model:
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->user_password;
}
Laravel's out-of-the-box App\User
Model extends Illuminate\Foundation\Auth\User
, which uses the Illuminate\Auth\Authenticatable
trait. That trait is just a convenience for satisfying the conditions of the Illuminate\Contracts\Auth\Authenticatable
interface, one of which is to have basically a getter for whatever your password field is named. You'd be overriding this.
The word 'password' in the context of grant-types is an entirely different thing by the way, and not something you should have to change like that. That has more to do with a configuration reference, and not a database field.