Akshay Deshmukh
Akshay Deshmukh

Reputation: 1292

Laravel passport refresh token

I am using a Laravel version 5.5 using Passport for authentication. I have successfully create the token and can access it using the auth:api middleware.

But whenever user login into system it create new token for that user. I just want to refresh user last token and send it back instead of creating a new token.

I have used the following code to generate auth token

$token = $user->createToken('string-'.$user->id)->accessToken;

It generate the token with 1075 characters but when i checked in database table oauth_access_tokens it shows me the token with 80 characters.

How can i get last generated token using 80 character token and refresh it and send it back?

Thanks in Advance

Upvotes: 4

Views: 8702

Answers (2)

Usama Munir
Usama Munir

Reputation: 635

I've done something like.

Created an endpoint for grant refresh token. and in my controller,

public function userRefreshToken(Request $request)
{
$client = DB::table('oauth_clients')
    ->where('password_client', true)
    ->first();

$data = [
    'grant_type' => 'refresh_token',
    'refresh_token' => $request->refresh_token,
    'client_id' => $client->id,
    'client_secret' => $client->secret,
    'scope' => ''
];
$request = Request::create('/oauth/token', 'POST', $data);
$content = json_decode(app()->handle($request)->getContent());

return response()->json([
    'error' => false,
    'data' => [
        'meta' => [
            'token' => $content->access_token,
            'refresh_token' => $content->refresh_token,
            'type' => 'Bearer'
        ]
    ]
], Response::HTTP_OK);
}

Upvotes: 0

Ismoil  Shifoev
Ismoil Shifoev

Reputation: 6011

If your application issues short-lived access tokens, users will need to refresh their access tokens via the refresh token that was provided to them when the access token was issued. In this example, we'll use the Guzzle HTTP library to refresh the 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);

This /oauth/token route will return a JSON response containing access_token, refresh_token, and expires_in attributes. The expires_in attribute contains the number of seconds until the access token expires.

Upvotes: 3

Related Questions