Skip to content

Instantly share code, notes, and snippets.

@salipro4ever
Last active May 2, 2018 03:54
Show Gist options
  • Save salipro4ever/1fd7961e1a861a800527c67d75f4ea2b to your computer and use it in GitHub Desktop.
Save salipro4ever/1fd7961e1a861a800527c67d75f4ea2b to your computer and use it in GitHub Desktop.
Understanding laravel passport scope

Define Scopes

You may define your API's scopes using the Passport::tokensCan method in the boot method of your AuthServiceProvider. Client can not request access_token with scopes if it does not define in tokensCan already.

use Laravel\Passport\Passport;

Passport::tokensCan([
    'place-orders' => 'Place orders',
    'check-status' => 'Check order status',
]);

Client call

Client will sent a request with scope parameter. Note that client only can request scopes that define on server already.

$query = http_build_query([
        'client_id' => 'client-id',
        'redirect_uri' => 'http://example.com/callback',
        'response_type' => 'code',
        'scope' => 'place-orders check-status',
    ]);

    return redirect('http://your-app.com/oauth/authorize?'.$query);

Check scope

To get started, add the following middleware to the $routeMiddleware property of your app/Http/Kernel.php file:

'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,

middleware
Note that route must use auth:api,unless scope not apply

Route::get('/orders', function () {
    // Access token has both "check-status" and "place-orders" scopes...
})->middleware('scopes:check-status,place-orders');

Route::get('/orders', function () {
    // Access token has either "check-status" or "place-orders" scope...
})->middleware('scope:check-status,place-orders');

controller

use Illuminate\Http\Request;

Route::get('/orders', function (Request $request) {
    if ($request->user()->tokenCan('place-orders')) {
        //
    }
});

Others

Passport::scopes() or Passport::hasScope();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment