1
votes

I am developing an REST API using Laravel 5.4 (passport).

I want the user to get the access token on signup without making another http request. i have gone thorough Laravel documentation. but there is no direct way to get the access token. something like:-

$token = $user->getOathToken($user_id);

Passport documentation for password grant token

In documentation they provide something like this:

    $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);

I don't want to make another http request. is there any way to avoid it?

2

2 Answers

2
votes

After research, here is a class that does the job you're looking for

use Laravel\Passport\Http\Controllers\ConvertsPsrResponses;
use League\OAuth2\Server\AuthorizationServer;
use Zend\Diactoros\Response as Psr7Response;
use Zend\Diactoros\ServerRequest;

class TokenProvider
{
    use ConvertsPsrResponses;

    /**
     * @var AuthorizationServer
     */
    private $authServer;

    public function __construct()
    {

        $this->authServer = resolve(AuthorizationServer::class);
    }

    public function getToken(string $email, string $password)
    {
        $data = [
            'grant_type' => 'password',
            'client_id' => config('services.passport.client_id'),
            'client_secret' => config('services.passport.client_secret'),
            'username' => $email,
            'password' => $password
        ];
        $request = new ServerRequest($data);
        $request = $request->withParsedBody($data);
        $response = $this->convertResponse($this->authServer->respondToAccessTokenRequest($request,new Psr7Response));
        return json_decode($response->content())->access_token;
    }

}
1
votes

There isn't a method available for doing what you want to do. You could have a look at

\Laravel\Passport\Http\Controllers\AccessTokenController@issueToken

Which is the controller method that handles the /oauth/token route. And look at passing it the required parameters without doing it as a POST request.