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

Oauth2 Php Laravel Package

authbucket/oauth2-php

Standards-compliant OAuth 2.0 (RFC6749) server library for PHP. Includes a Silex-based service provider for demos/tests and supports custom models/model managers (e.g., Doctrine) for tokens, clients, users, and scopes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use Case

  1. Install the Package:

    composer require authbucket/oauth2-php:~5.0
    

    Add to composer.json under require:

    "authbucket/oauth2-php": "~5.0"
    
  2. Basic Laravel Integration (since Laravel uses Symfony components):

    • Register the Silex provider in a Laravel service provider (e.g., AuthServiceProvider):
      use AuthBucket\OAuth2\Silex\Provider\AuthBucketOAuth2ServiceProvider;
      
      public function register()
      {
          $this->app->register(new AuthBucketOAuth2ServiceProvider());
      }
      
  3. Define Routes (in routes/api.php or routes/web.php):

    Route::get('/oauth2/authorize', ['uses' => 'authbucket_oauth2.authorization_controller@indexAction'])
         ->name('oauth2.authorize');
    Route::post('/oauth2/token', ['uses' => 'authbucket_oauth2.token_controller@indexAction'])
         ->name('oauth2.token');
    Route::match(['get', 'post'], '/oauth2/debug', ['uses' => 'authbucket_oauth2.debug_controller@indexAction'])
         ->name('oauth2.debug');
    
  4. First Use Case: Password Grant Flow

    • Configure a user provider (e.g., Laravel’s Eloquent User model):
      $this->app['authbucket_oauth2.user_provider'] = $this->app->make('App\Repositories\UserRepository');
      
    • Protect the token endpoint with a firewall (Laravel’s auth:api or custom):
      $this->app['security.firewalls'] = [
          'oauth2_token' => [
              'pattern' => '^/oauth2/token$',
              'oauth2_token' => true,
          ],
      ];
      
    • Test with a POST request to /oauth2/token:
      {
          "grant_type": "password",
          "username": "user@example.com",
          "password": "password",
          "client_id": "your_client_id",
          "client_secret": "your_client_secret"
      }
      

Implementation Patterns

Workflows

1. Authorization Code Flow (Common for SPAs/Mobile Apps)

  • Frontend (SPA/Mobile): Redirect user to /oauth2/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=REDIRECT_URI.
  • Backend (Laravel):
    • Handle the redirect in authorization_controller.
    • Exchange the code for a token via /oauth2/token with grant_type=authorization_code.
  • Laravel Integration: Use Laravel’s session or cookies to manage the redirect after authorization.

2. Client Credentials Flow (Machine-to-Machine)

  • Use Case: API-to-API communication (e.g., microservices).
  • Implementation:
    $client = new \AuthBucket\OAuth2\Client\Client(
        $this->app['authbucket_oauth2.client_manager'],
        ['client_id' => 'CLIENT_ID', 'client_secret' => 'CLIENT_SECRET']
    );
    $token = $client->getAccessToken('client_credentials');
    
  • Laravel Tip: Store client credentials in Laravel’s config/services.php or environment variables.

3. Resource Server Protection

  • Protect API endpoints with the oauth2_resource firewall:
    $this->app['security.firewalls'] = [
        'api' => [
            'pattern' => '^/api/protected',
            'oauth2_resource' => [
                'scope' => ['read', 'write'], // Optional: Enforce scopes
            ],
        ],
    ];
    
  • Laravel Middleware Alternative: Create a middleware to validate tokens:
    use AuthBucket\OAuth2\ResourceServer\TokenValidator;
    
    public function handle($request, Closure $next)
    {
        $validator = new TokenValidator(
            $this->app['authbucket_oauth2.token_storage'],
            $this->app['authbucket_oauth2.client_manager']
        );
        $validator->validate($request->bearerToken());
        return $next($request);
    }
    

4. Custom User Provider (Laravel Eloquent)

  • Implement AuthBucket\OAuth2\UserProviderInterface:
    use AuthBucket\OAuth2\UserProviderInterface;
    use App\Models\User;
    
    class LaravelUserProvider implements UserProviderInterface
    {
        public function loadUserByUsername($username)
        {
            return User::where('email', $username)->first();
        }
    
        public function refreshUser(UserInterface $user)
        {
            return $this->loadUserByUsername($user->getUsername());
        }
    
        public function supportsClass($class)
        {
            return $class === User::class;
        }
    }
    
  • Register it in Laravel:
    $this->app['authbucket_oauth2.user_provider'] = $this->app->make(LaravelUserProvider::class);
    

5. Token Storage (Database Backend)

  • Replace the default in-memory storage with a database-backed solution:
    $this->app['authbucket_oauth2.model_manager.factory'] = function ($app) {
        return new \AuthBucket\OAuth2\Model\Manager\DoctrineManager(
            $app['doctrine.orm.entity_manager'],
            'App\Models\OAuth2AccessToken',
            'App\Models\OAuth2RefreshToken',
            'App\Models\OAuth2Client'
        );
    };
    
  • Laravel Eloquent Models: Create models for AccessToken, RefreshToken, and Client extending AuthBucket\OAuth2\Model\Entity.

Integration Tips

  1. Laravel-Specific:

    • Use Laravel’s Hash facade to encode passwords for the password grant type:
      $app['security.default_encoder'] = function () {
          return new \Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder(); // Or use Laravel's Hash::make()
      };
      
    • Leverage Laravel’s Auth facade for user management where possible.
  2. CORS Configuration:

    • Ensure your /oauth2/authorize and /oauth2/token endpoints are CORS-enabled for SPAs:
      $this->app->middleware('cors', ['except' => ['oauth2.*']]);
      
  3. Logging:

    • Integrate with Laravel’s logging:
      $this->app['monolog.logger.oauth2'] = function () {
          return $this->app->make('logger')->withFields(['service' => 'oauth2']);
      };
      
  4. Testing:

    • Use Laravel’s HTTP tests to simulate OAuth2 flows:
      $response = $this->post('/oauth2/token', [
          'grant_type' => 'password',
          'username' => 'user@example.com',
          'password' => 'password',
          'client_id' => 'test_client',
          'client_secret' => 'test_secret',
      ]);
      $response->assertJsonStructure(['access_token', 'expires_in']);
      

Gotchas and Tips

Pitfalls

  1. Firewall Configuration:

    • Issue: Forgetting to protect the /oauth2/token endpoint can lead to unauthorized token issuance.
    • Fix: Always use the oauth2_token firewall for the token endpoint:
      'oauth2_token' => [
          'pattern' => '^/oauth2/token$',
          'oauth2_token' => true,
      ],
      
  2. State Parameter:

    • Issue: CSRF attacks if the state parameter is not validated in the authorization flow.
    • Fix: Use Laravel’s session to store and validate the state:
      // In authorization_controller
      $state = $request->query->get('state');
      if (!hash_equals(session('oauth2_state'), $state)) {
          throw new \Symfony\Component\HttpKernel\Exception\BadRequestHttpException('Invalid state parameter.');
      }
      
  3. Redirect URIs:

    • Issue: Open redirect vulnerabilities if redirect_uri is not validated.
    • Fix: Whitelist allowed URIs in your client configuration:
      $client->setAllowedRedirectUris(['https://yourapp.com/callback']);
      
  4. Token Expiration:

    • Issue: Tokens not being refreshed automatically.
    • Fix: Implement a middleware to refresh tokens before they expire:
      public function handle($request, Closure $next)
      {
          $token = $request->bearerToken();
          if ($token && $this->isTokenExpired($token)) {
              $token = $this->refreshToken($token);
              $request->headers->set('Authorization', 'Bearer ' . $token);
          }
          return $next($request);
      }
      
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.
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
spatie/mailcoach-vapor