简体   繁体   中英

Laravel Passport Password Grant Refresh Token

Trying to wrap my head around using Laravel's Passport with mobile clients. The Password Grant type of authentication seems to be the way to go, and i have it working with my iOS app, however i can't get token refreshing to work.

When authenticating i get a token and a refresh token which i store, however when the token expires, calling the oauth/token/refresh route doesn't work. The route is using the web middleware which means my app using the api route can't access it. I'm not sure if they intended for mobile clients to never refresh or if they wanted you to roll your own refreshing? If anyone has insight on how this is supposed to work, that'd be great.

The oauth/token/refresh route is not for refreshing access tokens. It is used to refresh transient tokens, which are used when you consume your own API from your javascript.

To use your refresh_token to refresh your access token, you need to call the oauth/token route with the grant_type of refresh_token .

This is the example provided by the documentation :

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

One note about scopes, when you refresh the token, you can only obtain identical or narrower scopes than the original access token. If you attempt to get a scope that was not provided by the original access token, you will get an error.

I've done something like.

  1. 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM