I tried to find the existing laravel package to solve my problem but still not and then I returned to laravel docs and read the Laravel Passport for more detail.
On the section, you will see
When authenticating using the password grant, Passport will use the email attribute of your model as the "username". However, you may customize this behavior by defining a findForPassport method on your model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* Find the user instance for the given username.
*
* @param string $username
* @return \App\User
*/
public function findForPassport($username)
{
return $this->where('username', $username)->first();
}
}
and block this code:
Customizing The Password Validation
When authenticating using the password grant, Passport will use the password attribute of your model to validate the given password. If your model does not have a password attribute or you wish to customize the password validation logic, you can define a validateForPassportPasswordGrant method on your model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* Validate the password of the user for the Passport password grant.
*
* @param string $password
* @return bool
*/
public function validateForPassportPasswordGrant($password)
{
return Hash::check($password, $this->password);
}
}
you just register validateForPassportPasswordGrant($password) method on the user model and then return true.
After that, you need to create methods which allow you can anywhere if you need with the code:
public function getTokenWithoutPassword($username)
{
$client = DB::table('oauth_clients')
->where('password_client', true)
->get()[0];
$data = [
'grant_type' => 'password',
'client_id' => $client->id,
'client_secret' => $client->secret,
'username' => $username,
'password' => 'what-is-your-password', // just leave whatever string
'scope' => '',
];
$response = Request::create(url('/oauth/token'), 'POST', $data);
return json_decode(app()->handle($response)->getContent());
}
this method will the result:
{
"token_type": "Bearer",
"expires_in": xxxx,
"access_token": "xxxx",
"refresh_token": "xxxx",
}