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

alb/oauth2-php

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Installation

    composer require friends-of-symfony/oauth2-php
    

    (Note: Redirect to FriendsOfSymfony/oauth2-php as per README.)

  2. Basic Server Initialization

    use FriendsOfSymfony\OAuth2\Server;
    use FriendsOfSymfony\OAuth2\Storage\MemoryStorage;
    
    $server = new Server();
    $server->setStorage(new MemoryStorage()); // Replace with DB/Redis in production
    $server->boot();
    
  3. First Use Case: Token Endpoint

    $request = Request::createFromGlobals();
    $response = $server->handleTokenRequest($request);
    $response->send();
    
  4. Key Files to Review

    • config/oauth2.php (if creating custom config)
    • app/Providers/OAuthServiceProvider.php (for binding storage)
    • routes/api.php (for endpoint routing)

Implementation Patterns

Core Workflows

  1. Authorization Code Flow (Most Common)

    // 1. Redirect user to auth endpoint
    $authUrl = $server->getAuthorizationUrl(
        $clientId,
        $redirectUri,
        ['scope' => 'read write']
    );
    
    // 2. Handle callback
    $request = Request::createFromGlobals();
    $response = $server->handleAuthorizationRequest($request);
    
  2. Resource Owner Password Credentials (Legacy)

    $token = $server->getAccessToken(
        $clientId,
        $clientSecret,
        $username,
        $password,
        $scope = null
    );
    
  3. Token Validation in API

    $request = Request::createFromGlobals();
    $token = $server->validateAuthenticatedRequest($request);
    if (!$token) {
        return response()->json(['error' => 'invalid_token'], 401);
    }
    

Integration Tips

  • Laravel Middleware for Token Validation

    namespace App\Http\Middleware;
    
    use Closure;
    use FriendsOfSymfony\OAuth2\Server;
    
    class ValidateOAuthToken
    {
        protected $server;
    
        public function __construct(Server $server)
        {
            $this->server = $server;
        }
    
        public function handle($request, Closure $next)
        {
            if (!$this->server->validateAuthenticatedRequest($request)) {
                return response()->json(['error' => 'invalid_token'], 401);
            }
            return $next($request);
        }
    }
    
  • Custom Storage Backend (e.g., Eloquent)

    use FriendsOfSymfony\OAuth2\Storage\StorageInterface;
    use App\Models\OAuthClient;
    
    class EloquentStorage implements StorageInterface
    {
        public function getClientDetails($clientId)
        {
            return OAuthClient::where('id', $clientId)->first();
        }
        // Implement other required methods...
    }
    
  • Scopes Handling

    // Register scopes in storage
    $storage->setScope('read', ['description' => 'Read access']);
    $storage->setScope('write', ['description' => 'Write access']);
    
    // Validate scopes in API
    $token = $server->validateAuthenticatedRequest($request);
    if (!$token->getScope()->hasScope('read')) {
        abort(403);
    }
    

Gotchas and Tips

Common Pitfalls

  1. Draft Version Mismatch

    • The server implements draft-21, but the client still uses draft-10.
    • Fix: Use a separate client library (e.g., league/oauth2-client) for consistency.
  2. MemoryStorage for Production

    • MemoryStorage is not persistent across requests.
    • Fix: Implement StorageInterface with a database (e.g., Eloquent, Doctrine).
  3. CSRF Protection

    • The library does not handle CSRF tokens by default.
    • Fix: Add middleware to validate state parameter in auth flow.
  4. Redirect URI Validation

    • Always validate redirect_uri against registered clients.
    • Example:
      $client = $storage->getClientDetails($clientId);
      if ($client->getRedirectUri() !== $request->get('redirect_uri')) {
          throw new \RuntimeException('Invalid redirect URI');
      }
      

Debugging Tips

  • Enable Verbose Logging

    $server->setLogger(new \Monolog\Logger('oauth', [
        new \Monolog\Handler\StreamHandler(storage_path('logs/oauth.log'))
    ]));
    
  • Check Response Headers

    • OAuth2 errors are often returned as JSON with HTTP status codes (e.g., 400 Bad Request for invalid requests).
  • Token Expiry Handling

    • Use Token::getExpiration() to check expiry and refresh tokens if needed.

Extension Points

  1. Custom Grant Types

    $server->addGrantType(new \FriendsOfSymfony\OAuth2\Grant\CustomGrantType());
    
  2. Token Enhancements

    // Extend Token class
    class ExtendedToken extends \FriendsOfSymfony\OAuth2\Token\Token
    {
        public function getCustomClaim()
        {
            return $this->claims['custom_claim'] ?? null;
        }
    }
    
  3. Event Dispatching

    • Listen for events like authentication.success or token.issued:
    $server->on('authentication.success', function ($token) {
        // Log or process token
    });
    

Configuration Quirks

  • State Parameter

    • Always generate a unique state for authorization requests to prevent CSRF.
    • Example:
      $state = bin2hex(random_bytes(32));
      session(['oauth_state' => $state]);
      $authUrl = $server->getAuthorizationUrl($clientId, $redirectUri, ['state' => $state]);
      
  • Scope Validation

    • Scopes are case-sensitive and must match exactly what’s registered in storage.
  • Client Secrets

    • Ensure client_secret is hashed in storage if using a database backend (e.g., bcrypt).
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope