Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Passport Modern Scopes Laravel Package

n3xt0r/laravel-passport-modern-scopes

Attribute-based OAuth scope enforcement for Laravel Passport. Declare required scopes directly on controllers/actions via PHP 8 attributes, then enforce them with a single middleware. Keeps routes clean and auth rules close to the code they protect.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require n3xt0r/laravel-passport-modern-scopes
    

    Run migrations:

    php artisan migrate
    
  2. Publish Config

    php artisan vendor:publish --provider="N3xt0r\PassportModernScopes\PassportModernScopesServiceProvider" --tag="config"
    

    Review config/passport-modern-scopes.php for default scope definitions.

  3. First Use Case Define a scope in config/passport-modern-scopes.php:

    'scopes' => [
        'admin' => [
            'attributes' => ['role' => 'admin'],
        ],
        'user:profile' => [
            'attributes' => ['user_id' => auth()->id()],
        ],
    ],
    

    Assign scopes to a user:

    $user->scopes()->sync(['admin', 'user:profile']);
    

Implementation Patterns

Workflow: Scope Assignment & Enforcement

  1. Assign Scopes Dynamically

    // In a controller or service
    $user->scopes()->sync($request->scopes);
    
  2. Check Scopes in API

    // Middleware or controller
    if (!PassportModernScopes::hasScope('admin')) {
        abort(403, 'Admin scope required');
    }
    
  3. Scope-Based Route Groups

    Route::middleware(['auth:api', 'scope:admin'])->group(function () {
        // Admin-only routes
    });
    

Integration with Passport

  • Token Creation

    $token = $user->createToken('API Token', ['admin', 'user:profile']);
    
  • Custom Scope Logic Extend N3xt0r\PassportModernScopes\Scopes\Scope for complex rules:

    class CustomScope extends Scope {
        public function check($user, $request) {
            return $user->isActive() && parent::check($user, $request);
        }
    }
    

Common Patterns

  • Role-Based Scopes
    'scopes' => [
        'role:editor' => [
            'attributes' => ['role' => ['editor', 'admin']],
        ],
    ],
    
  • Dynamic Attribute Scopes
    'scopes' => [
        'user:team' => [
            'attributes' => ['team_id' => fn($user) => $user->team_id],
        ],
    ],
    

Gotchas and Tips

Pitfalls

  1. Scope Caching

    • Scopes are cached per-user. Clear cache after dynamic scope changes:
      php artisan passport-modern-scopes:clear-cache
      
    • Or manually:
      PassportModernScopes::clearCache($user);
      
  2. Attribute Mismatch

    • Ensure attributes in config match the user model’s fields. Use fn() for computed values:
      'attributes' => ['team_id' => fn($user) => $user->currentTeam->id],
      
  3. Middleware Conflicts

    • If using scope: middleware, ensure it runs after auth:api in $routeMiddleware.
  4. Token Scope Persistence

    • Scopes are tied to the user, not the token. Revoking a token doesn’t remove scopes unless the user’s scopes are updated.

Debugging

  • Log Scope Checks Enable debug mode in config:

    'debug' => env('PASSPORT_SCOPES_DEBUG', false),
    

    Check logs for failed scope validations.

  • Inspect User Scopes

    dd($user->scopes); // Collection of assigned scopes
    

Extension Points

  1. Custom Scope Classes Override N3xt0r\PassportModernScopes\Scopes\ScopeResolver to add logic:

    public function resolve($scopeName) {
        return match ($scopeName) {
            'vip' => new VipScope(),
            default => parent::resolve($scopeName),
        };
    }
    
  2. Event Listeners Listen for scope changes:

    // In EventServiceProvider
    protected $listen = [
        'N3xt0r\PassportModernScopes\Events\ScopesSynced' => [
            \App\Listeners\LogScopeChange::class,
        ],
    ];
    
  3. API Resource Filtering Use the PassportModernScopes::getAllowedAttributes() helper to filter Eloquent results:

    $allowed = PassportModernScopes::getAllowedAttributes('user:profile');
    return User::where($allowed)->get();
    

Config Quirks

  • Default Scopes Set default_scopes in config to auto-assign scopes on user creation:
    'default_scopes' => ['user:profile'],
    
  • Scope Naming Use kebab-case (e.g., user:profile) for consistency with Passport’s token scope format.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
monarobase/country-list
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity