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 Authorization Core Laravel Package

n3xt0r/laravel-passport-authorization-core

Core components for building OAuth2 authorization flows with Laravel Passport. Provides reusable helpers and abstractions to standardize consent/approval handling and authorization logic, making it easier to implement custom Passport authorization endpoints and UI.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require n3xt0r/laravel-passport-authorization-core:^1.3.0
    php artisan passport:install
    php artisan vendor:publish --provider="N3xt0r\PassportAuthorizationCore\PassportAuthorizationCoreServiceProvider" --tag="migrations"
    php artisan migrate
    
  2. Configure Passport Ensure HasApiTokens is added to your User model and Passport is bootstrapped in AuthServiceProvider. Note: This package now supports Laravel 13.

  3. Define a Resource Create a resource class (e.g., app/Models/Post.php):

    use N3xt0r\PassportAuthorizationCore\Contracts\AuthorizableResource;
    
    class Post implements AuthorizableResource
    {
        public static function getAuthorizableActions(): array
        {
            return ['view', 'edit', 'delete'];
        }
    }
    
  4. First Use Case: Scope-Based Authorization In a controller, enforce scope checks:

    use N3xt0r\PassportAuthorizationCore\Facades\PassportAuthorization;
    
    public function show(Post $post)
    {
        PassportAuthorization::authorize($post, 'view');
    }
    

Implementation Patterns

Core Workflows

  1. Resource-Action Mapping

    • Define actions in getAuthorizableActions() for each resource.
    • Use PassportAuthorization::authorize($resource, $action) in controllers/middleware.
  2. Dynamic Scopes Attach scopes to user roles dynamically:

    // In a User model observer or service
    $user->scopes()->attach('post:view');
    
  3. Middleware Integration Protect routes globally:

    Route::middleware(['auth:api', 'scope'])->group(function () {
        // Routes requiring at least one scope
    });
    
  4. Policy Integration Combine with Laravel’s native policies:

    public function update(Request $request, Post $post)
    {
        $this->authorize('update', $post);
        PassportAuthorization::authorize($post, 'edit');
    }
    

Integration Tips

  • Passport Scopes: Map custom scopes to resource-actions in config/passport-authorization.php:
    'scopes' => [
        'post:view' => ['resource' => Post::class, 'action' => 'view'],
    ],
    
  • API Resources: Extend JsonResource to include scope metadata:
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'actions' => PassportAuthorization::getAuthorizedActions($this, $request->user()),
        ];
    }
    
  • Laravel 13 Compatibility: Ensure your AuthServiceProvider and User model are updated for Laravel 13 conventions if applicable.

Gotchas and Tips

Pitfalls

  1. Scope Mismatch Errors

    • Issue: PassportAuthorization::authorize() fails silently or throws AuthorizationException.
    • Fix: Verify scopes are attached to the user and mapped in config. Use:
      PassportAuthorization::getAuthorizedActions($resource, $user);
      
      to debug allowed actions.
  2. Caching Conflicts

    • Issue: Scopes cached in oauth_scopes table may not reflect real-time changes.
    • Fix: Clear cached scopes after bulk updates:
      php artisan passport:clear-scopes-cache
      
  3. Resource Not Authorizable

    • Issue: Class 'App\Models\Post' does not implement AuthorizableResource.
    • Fix: Ensure all resources implement AuthorizableResource and define getAuthorizableActions().
  4. Laravel 13 Migration Issues

    • Issue: Potential conflicts with Laravel 13's updated service providers or authentication system.
    • Fix: Review the AuthServiceProvider and ensure the PassportAuthorizationCoreServiceProvider is registered correctly. If using Laravel 13's new authentication system, verify compatibility by checking the package's documentation or GitHub issues.

Debugging Tips

  • Log Scopes: Enable debug mode in config:

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

    Check Laravel logs for scope resolution details.

  • Test with Tinker:

    php artisan tinker
    >>> $user = App\Models\User::first();
    >>> $post = App\Models\Post::first();
    >>> \N3xt0r\PassportAuthorizationCore\Facades\PassportAuthorization::getAuthorizedActions($post, $user);
    

Extension Points

  1. Custom Authorizers Override the default authorizer:

    PassportAuthorization::setAuthorizer(new CustomAuthorizer());
    
  2. Event Listeners Listen for scope attachment/detachment:

    // In EventServiceProvider
    protected $listen = [
       'N3xt0r\PassportAuthorizationCore\Events\ScopeAttached' => [
           \App\Listeners\LogScopeChange::class,
       ],
    ];
    
  3. Database Schema Extend the oauth_scopes table for custom metadata:

    Schema::table('oauth_scopes', function (Blueprint $table) {
        $table->string('metadata')->nullable();
    });
    
  4. Laravel 13 Customization

    • Service Provider: If you encounter issues with the PassportAuthorizationCoreServiceProvider, ensure it is bootstrapped correctly in config/app.php under the providers array.
    • Authentication: If using Laravel 13's new authentication scaffolding, ensure the HasApiTokens trait is correctly applied to your User model.
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky