4

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

Akshay Deshmukh
  • 1,242
  • 1
  • 16
  • 31

2 Answers2

3

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.

Ismoil Shifoev
  • 5,512
  • 3
  • 24
  • 32
  • Thank you for quick response. Can you please explain exactly what values i need to pass in `form_params`? – Akshay Deshmukh Dec 14 '18 at 09:01
  • @AkshayDeshmukh you must send old refresh-token (`'refresh_token' => 'the-refresh-token',`) and this code produces a new token and refresh-refresh – Vajiheh Habibi Feb 05 '19 at 20:33
0

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);
}
Usama Munir
  • 589
  • 9
  • 11