How to use Laravel Passport with Password Grant Tokens?

If you are consuming your own api then you don’t need to call http://example.com/oauth/token
for user login because then you need to store client_id and client_secret at app side. Better you create an api for login and there you can check the credentials and generate the personal token.

public function login(Request $request)
{
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            // Authentication passed...
             $user = Auth::user();
             $token = $user->createToken('Token Name')->accessToken;

            return response()->json($token);
        }
}

Finally, there are a lot of endpoints that I get from passport that I
don’t think I will use for example: oauth/clients*,
oauth/personal-access-tokens* is there a way to remove them from the
endpoints published by passport?

You need to remove Passport::routes(); from AuthServiceProvider and manually put only required passport routes. I think you only need oauth/token route.

what exactly is “The-App” value for?

if you check oauth_access_tokens table it has name field. $user->createToken('Token Name')->accessToken; here the “Token Name” stored in name field.

How to use Laravel Passport with Password Grant Tokens?

To generate password grant token you have to store client_id and client_secret at app side (not recommended, check this ) and suppose if you have to reset the client_secret then the old version app stop working, these are the problems. To generate password grant token you have to call this api like you mention in step 3.

$http = new GuzzleHttp\Client;

$response = $http->post('http://your-app.com/oauth/token', [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'username' => '[email protected]',
        'password' => 'my-password',
        'scope' => '',
    ],
]);

return json_decode((string) $response->getBody(), true);

Generate token from refresh_token

$http = new GuzzleHttp\Client;

$response = $http->post('http://your-app.com/oauth/token', [
    'form_params' => [
        'grant_type' => 'refresh_token',
        'refresh_token' => 'the-refresh-token',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'scope' => '',
    ],
]);

return json_decode((string) $response->getBody(), true);

You can look this https://laravel.com/docs/5.6/passport#implicit-grant-tokens too.

Leave a Comment