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

Oauth Server Bundle Laravel Package

chaima409/oauth-server-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require chaima409/oauth-server-bundle

Add to config/bundles.php:

Chaima409\OAuthServerBundle\Chaima409OAuthServerBundle::class => ['all' => true],
  1. Configuration: Enable the bundle in config/packages/chaima409_oauth_server.yaml (create if missing):

    chaima409_oauth_server:
        db_driver: orm          # or 'pdo' for PDO-based storage
        token_param_name:       # Customize token param if needed
            access_token: access_token
            refresh_token: refresh_token
        access_token_lifetime: 3600  # Default: 1 hour (in seconds)
        refresh_token_lifetime: 2592000  # Default: 30 days
    
  2. First Use Case:

    • Generate a Client: Use the fos_oauth_server:client:create command:
      php bin/console fos_oauth_server:client:create --redirect-uri=http://localhost --grant-types=password,refresh_token
      
    • Authenticate via OAuth: Send a POST request to /oauth/v2/token with:
      {
        "grant_type": "password",
        "client_id": "your_client_id",
        "client_secret": "your_client_secret",
        "username": "user@example.com",
        "password": "password"
      }
      
      Response:
      {
        "access_token": "abc123...",
        "expires_in": 3600,
        "refresh_token": "xyz456..."
      }
      
  3. Where to Look First:

    • Doctrine Entities: Check src/Entity/ for Client, AccessToken, and RefreshToken entities (auto-generated if using ORM).
    • Routing: OAuth endpoints are auto-configured under /oauth/v2/.
    • Documentation: Focus on Resources/doc/index.md for grant types, scopes, and customization.

Implementation Patterns

Core Workflows

  1. Client Management:

    • Dynamic Clients: Create clients programmatically:
      $client = new Client();
      $client->setRandomId();
      $client->setSecret('secure_secret');
      $client->addRedirectUri('https://yourapp.com/callback');
      $client->addGrantType('password');
      $em->persist($client);
      $em->flush();
      
    • Grant Types: Support authorization_code, password, refresh_token, client_credentials. Enable/disable via YAML:
      chaima409_oauth_server:
          grant_types:
              - password
              - refresh_token
      
  2. Token Handling:

    • Access Tokens: Automatically expire after access_token_lifetime. Extend lifetime via:
      $token = $this->get('chaima409_oauth_server.token_manager')->createAccessToken($client, $user, ['scope1', 'scope2'], 7200); // 2 hours
      
    • Refresh Tokens: Use refresh_token grant to issue new access tokens:
      POST /oauth/v2/token
      grant_type=refresh_token&refresh_token=xyz456...
      
  3. Authentication Integration:

    • User Provider: Extend UserProvider to validate credentials:
      use Chaima409\OAuthServerBundle\Security\User\UserProviderInterface;
      
      class CustomUserProvider implements UserProviderInterface {
          public function loadUserByUsername($username) {
              // Your logic to fetch user
          }
      }
      
      Register as a service:
      services:
          chaima409_oauth_server.user_provider:
              class: App\Security\CustomUserProvider
      
  4. Scopes:

    • Define scopes in YAML:
      chaima409_oauth_server:
          scopes:
              read: Grants read access
              write: Grants write access
      
    • Attach scopes to tokens:
      $token = $this->get('chaima409_oauth_server.token_manager')->createAccessToken($client, $user, ['read', 'write']);
      
  5. API Protection:

    • Protect routes with OAuth attribute:
      use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
      
      /**
       * @Security("is_granted('IS_AUTHENTICATED_FULLY')")
       */
      public function secureAction() { ... }
      
    • Or via firewall (Symfony security.yaml):
      access_control:
          - { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
      
  6. Custom Grant Types:

    • Implement GrantTypeInterface:
      use Chaima409\OAuthServerBundle\Grant\GrantTypeInterface;
      
      class CustomGrantType implements GrantTypeInterface {
          public function getName() { return 'custom'; }
          public function authenticate(Request $request) { ... }
      }
      
    • Register in services:
      services:
          chaima409_oauth_server.grant_type.custom:
              class: App\Grant\CustomGrantType
              tags:
                  - { name: chaima409_oauth_server.grant_type }
      

Gotchas and Tips

Common Pitfalls

  1. Token Storage:

    • ORM vs PDO: If using PDO, ensure your Token entities are properly mapped to the database. ORM is recommended for complex queries.
    • Token Cleanup: Refresh tokens and expired access tokens are not auto-pruned. Schedule a cron job or use Doctrine lifecycle callbacks to clean up:
      // In your RefreshToken entity
      public function __destruct() {
          if ($this->getExpiration() < new \DateTime()) {
              // Delete or mark as expired
          }
      }
      
  2. Security:

    • Client Secrets: Never hardcode client secrets. Use environment variables or Symfony’s parameter_bag.
    • HTTPS: Always enforce HTTPS for OAuth endpoints to prevent token interception.
    • CSRF: Disable CSRF protection for /oauth/v2/token in Symfony’s security config:
      security:
          access_control:
              - { path: ^/oauth/v2/token, roles: PUBLIC_ACCESS }
      
  3. Configuration Quirks:

    • Missing Routes: If OAuth endpoints (e.g., /oauth/v2/token) are not found, ensure:
      • The bundle is enabled in bundles.php.
      • No conflicting routes exist (e.g., from other bundles).
    • Doctrine Events: If using custom entities, listen for prePersist/preUpdate to auto-generate IDs or timestamps:
      $client->setRandomId(); // For Client entity
      $token->setCreatedAt(new \DateTime()); // For Token entities
      
  4. Debugging:

    • Token Validation: Use the TokenManager to validate tokens manually:
      $tokenManager = $this->get('chaima409_oauth_server.token_manager');
      $token = $tokenManager->findToken('access_token_here');
      if (!$token || $token->isExpired()) {
          throw new \RuntimeException('Invalid token');
      }
      
    • Logging: Enable debug mode to log OAuth events:
      chaima409_oauth_server:
          debug: true
      
  5. Extension Points:

    • Custom Responses: Override token response format by extending the TokenResponse class and configuring a custom service:
      services:
          chaima409_oauth_server.response:
              class: App\OAuth\CustomTokenResponse
              public: false
      
    • Event Listeners: Listen to OAuth events (e.g., oauth.server.token.created):
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      use Chaima409\OAuthServerBundle\Event\TokenEvent;
      
      class OAuthEventSubscriber implements EventSubscriberInterface {
          public static function getSubscribedEvents() {
              return [
                  TokenEvent::TOKEN_CREATED => 'onTokenCreated',
              ];
          }
      
          public function onTokenCreated(TokenEvent $event) {
              // Custom logic (e.g., log tokens, send notifications)
          }
      }
      
  6. Performance:

    • Token Lookup: For high-traffic apps, cache token validation results:
      $cache = $this->get('cache.app');
      $cacheKey = 'oauth_token_' . $tokenId;
      if (!$cache->has($cacheKey)) {
          $token = $tokenManager->findToken($tokenId);
          $cache->set($cacheKey, $token, 60); // Cache for 60 seconds
      }
      
  7. Testing:

    • Mock Tokens: Use the `
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware