Is there any way to use in laravel jwt-auth the authentication using username (or any custom column), instead of an email?
This is the existing code
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'));
}
I want to do Something like this
$credentials = $request->only('username', 'password');
One way is to put usernames in email column but that is a bad solution.
I've found a way here
We can grab a user from model (on the base of custom fields) like
// grab some user
$user = User::first();
and authenticate it manually.
$token = JWTAuth::fromUser($user);
Looking around, it looks like it is possible to do this by setting the credentials like so $credentials = $request->only('username', 'password');
.
So all up it would look like this:
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'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With