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

Cpjoauth2 Php Laravel Package

cpj/cpjoauth2-php

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require cpj/cpjoauth2-php
    

    Ensure your Laravel project meets the PHP (≥5.3.2) and Symfony HttpFoundation (≥2.0.0, <2.4.0-dev) requirements.

  2. Basic OAuth2 Server Initialization Register a route to handle OAuth2 requests (e.g., /oauth2):

    use Cpj\OAuth2\Server;
    use Symfony\Component\HttpFoundation\Request;
    
    Route::get('/oauth2', function (Request $request) {
        $server = new Server();
        $response = $server->handleRequest($request);
        return $response;
    });
    
  3. First Use Case: Token Endpoint Configure a storage adapter (e.g., PDO for databases) and define a Storage class to persist tokens/clients:

    use Cpj\OAuth2\Storage\PDO as Storage;
    
    $storage = new Storage(new PDO('mysql:host=localhost;dbname=oauth', 'user', 'pass'));
    $server = new Server($storage);
    

Implementation Patterns

Workflows

  1. Client Registration

    • Use the Client class to create OAuth2 clients:
      $client = new \Cpj\OAuth2\Client(
          'client_id',
          'client_secret',
          'http://client.example.com/callback',
          'confidential' // or 'public'
      );
      $storage->setClient($client);
      
  2. Authorization Code Flow

    • Redirect users to the authorization endpoint:
      $authUrl = $server->getAuthorizationUrl(
          'client_id',
          'http://client.example.com/callback',
          ['scope' => 'read write']
      );
      
    • Exchange the code for a token:
      $token = $server->getAccessToken('client_id', 'client_secret', 'authorization_code', ['code' => $code]);
      
  3. Resource Owner Password Flow

    • Directly authenticate and issue tokens:
      $token = $server->getAccessToken(
          'client_id',
          'client_secret',
          'password',
          ['username' => 'user', 'password' => 'pass', 'scope' => 'read']
      );
      

Integration Tips

  • Laravel Middleware: Wrap the Server::handleRequest() in middleware to validate tokens for protected routes:
    public function handle($request, Closure $next) {
        $server = new Server($this->storage);
        $request->attributes->add(['oauth_token' => $server->verifyAccessToken($request)]);
        return $next($request);
    }
    
  • PSR-7 Compatibility: Use Symfony\Component\HttpFoundation\Request/Response as inputs/outputs. For PSR-7 (e.g., Slim Framework), adapt requests/responses manually.
  • Scopes: Define and validate scopes via the Scope class or storage layer.

Gotchas and Tips

Pitfalls

  1. Draft-20 vs. Draft-10

    • The client implementation still follows draft-10, while the server supports draft-20. Ensure your OAuth2 client libraries align with draft-20 for full compatibility.
    • Workaround: Use a draft-20-compliant client (e.g., league/oauth2-client).
  2. Storage Layer Quirks

    • The package expects a custom Storage class (e.g., PDO, Redis). Default implementations are minimal; extend for complex logic:
      class CustomStorage extends \Cpj\OAuth2\Storage\PDO {
          public function getClient($clientId) {
              // Add custom logic (e.g., soft-deletes)
              return parent::getClient($clientId);
          }
      }
      
    • Tip: Use transactions for atomic operations (e.g., token issuance + client updates).
  3. HttpFoundation Dependency

    • The package relies on Symfony’s HttpFoundation. For Laravel, ensure no conflicts with native request/response handling.
    • Tip: Use Symfony\Component\HttpFoundation\Request::createFromGlobals() to bridge Laravel’s Illuminate\Http\Request.
  4. Token Validation

    • verifyAccessToken() returns false on failure. Always check:
      if (!$token = $server->verifyAccessToken($request)) {
          abort(401, 'Invalid token');
      }
      

Debugging

  • Enable Verbose Errors: Set error_details in the server constructor:
    $server = new Server($storage, ['error_details' => true]);
    
  • Log Storage Queries: Extend the Storage class to log SQL/Redis operations for debugging.

Extension Points

  1. Custom Grant Types Extend the GrantType class to support custom flows (e.g., JWT bearer):

    class JwtGrantType extends \Cpj\OAuth2\GrantType\AbstractGrantType {
        public function validate() { /* Custom logic */ }
    }
    

    Register it in the server:

    $server->addGrantType('urn:ietf:params:oauth:grant-type:jwt-bearer', new JwtGrantType());
    
  2. Token Enhancements Add custom claims to tokens by overriding the getAccessToken() method in your storage layer.

  3. Event System Use Laravel’s events to hook into OAuth2 flows (e.g., oauth2.token.issued). Example:

    event(new OAuth2TokenIssued($token));
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle