Laravel passport dynamic scopes

Viewed 1737

is there a way to set the dynamic scopes of laravel passport instead of typing manually?

I tried to create a table(MySql) with scope name and description, created a model Scope, but that model is not working in AuthServiceProvider

Passport::tokensCan([
           'view-dashboard' => 'View the contents of dashboard',
           'view-reports'   => 'View the detailed reports'
       ]);

How can i make the scopes dynamic ? i want to manage the scopes based on roles of users by creating some interface

Edit: I could relate the solution to my present situation, and it really makes sense but can you just help we with the code of line

$token->scopes = user_scopes;

i am getting an Exception error Attempt to assign property scopes of non-object in the user model as i have added your code in my User class as mentioned. Can you just clear me how can i fetch the scope ids?

1 Answers

You can try like:

  1. Create a user_scopes table attached to your users which has the scopes you want to assign to that user

  2. Overload the withAccessToken() method in your user Class, which is part of the HasApiTokens trait. Use this hook to pull your scopes from the database for that user and assign them to the access token:

public function withAccessToken($accessToken)
    {
        $this->accessToken = $accessToken;

        $token = $this->token();
        $token->scopes = $this->user_scopes;
        $token->save();

        return $this;
    }

If you want full flexibility, try extending and overriding the src/Bridge/ScopeRepository class

// in App\Providers\AppServiceProvider:

use App\ScopeRepository;
use Illuminate\Support\ServiceProvider;
use Laravel\Passport\Bridge\ScopeRepository as PassportScopeRepository;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(PassportScopeRepository::class, ScopeRepository::class);
    }
}

Follow here for the complete details. https://github.com/laravel/passport/issues/195

Related