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

cutwise/oauth-server-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cutwise/oauth-server-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Cutwise\OAuthServerBundle\CutwiseOAuthServerBundle::class => ['all' => true],
    ];
    
  2. Configuration: Override default settings in config/packages/cutwise_oauth_server.yaml:

    cutwise_oauth_server:
        db_driver: orm          # or 'mongodb'
        token_ttl: 3600         # Token lifetime (seconds)
        refresh_token_ttl: 86400
        access_token_ttl: 3600
    
  3. First Use Case: Generate an OAuth2 token via CLI:

    php bin/console fos:oauth-server:generate-token --username=test --password=secret
    

    Outputs a JSON response with access_token and refresh_token.


Implementation Patterns

Common Workflows

  1. Token Generation:

    • Manual: Use CLI (fos:oauth-server:generate-token) for testing.
    • Automated: Trigger via API endpoint (e.g., /api/auth/login):
      use Cutwise\OAuthServerBundle\Model\TokenManagerInterface;
      
      public function login(Request $request, TokenManagerInterface $tokenManager)
      {
          $credentials = json_decode($request->getContent(), true);
          $token = $tokenManager->createAccessToken(
              $credentials['username'],
              $credentials['password']
          );
          return new JsonResponse($token);
      }
      
  2. Protected Routes: Use Symfony’s access_control in security.yaml:

    access_control:
        - { path: ^/api/protected, roles: IS_AUTHENTICATED_FULLY }
    

    Decorate controllers with @Security("is_granted('IS_AUTHENTICATED_FULLY')").

  3. Refresh Tokens:

    $tokenManager->refreshAccessToken($refreshToken);
    
  4. Client Credentials Flow: Configure a client in config/packages/cutwise_oauth_server.yaml:

    clients:
        my_client:
            random_id: 'client_id_here'
            secret: 'client_secret_here'
            redirect_uri: 'https://example.com/callback'
    

    Generate tokens via:

    php bin/console fos:oauth-server:generate-client-token --client-id=my_client
    

Integration Tips

  • Laravel-Specific: Use Symfony’s HttpFoundation components via symfony/http-foundation for request/response handling. Example: Convert Symfony’s Request to Laravel’s Illuminate\Http\Request:

    $laravelRequest = Request::createFromGlobals();
    $symfonyRequest = new \Symfony\Component\HttpFoundation\Request(
        $laravelRequest->query->all(),
        $laravelRequest->request->all(),
        $laravelRequest->server->all(),
        $laravelRequest->cookies->all(),
        $laravelRequest->files->all(),
        $laravelRequest->server->get('REQUEST_METHOD')
    );
    
  • Database Migrations: Run migrations after installation:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  • Event Listeners: Subscribe to OAuth events (e.g., TokenCreatedEvent) in config/services.yaml:

    services:
        App\EventListener\OAuthListener:
            tags:
                - { name: kernel.event_listener, event: oauth.token.created, method: onTokenCreated }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle:

    • The package is unmaintained (last release: 2021). Fork or migrate to alternatives like league/oauth2-server if long-term support is needed.
    • Check for breaking changes if upgrading from FOSOAuthServerBundle (this is a fork).
  2. Token Storage:

    • Default ORM storage assumes Doctrine. For Laravel’s Eloquent, extend Cutwise\OAuthServerBundle\Model\TokenEntity:
      namespace App\Entity;
      
      use Cutwise\OAuthServerBundle\Model\TokenEntity as BaseTokenEntity;
      use Doctrine\ORM\Mapping as ORM;
      
      #[ORM\Entity]
      class TokenEntity extends BaseTokenEntity {}
      
    • Configure custom entity in config/packages/cutwise_oauth_server.yaml:
      token_entity: App\Entity\TokenEntity
      
  3. CSRF Protection:

    • Disable CSRF for OAuth endpoints in security.yaml:
      access_control:
          - { path: ^/oauth/v2/token, roles: PUBLIC_ACCESS }
      
    • Use stateless: true for token routes.
  4. Token Revocation:

    • Manually delete tokens via Doctrine:
      $tokenManager->deleteAccessToken($tokenId);
      
    • No built-in revocation endpoint; implement custom logic.

Debugging

  • Token Validation Errors: Enable debug mode and check Symfony’s profiler for OAuthException details. Common causes:

    • Invalid client_id/client_secret.
    • Expired tokens (adjust token_ttl in config).
  • Database Issues: Verify migrations ran and tables (oauth_access_token, oauth_refresh_token) exist.

Extension Points

  1. Custom Grant Types: Extend Cutwise\OAuthServerBundle\Grant\AbstractGrant and register in config/services.yaml:

    services:
        App\Grant\CustomGrant:
            tags:
                - { name: cutwise_oauth_server.grant, type: custom }
    
  2. Token Fields: Add custom fields to TokenEntity and update migrations:

    #[ORM\Column(type: 'string', nullable: true)]
    private $customField;
    
  3. Authentication Providers: Override Cutwise\OAuthServerBundle\Security\Authentication\Provider\OAuthProvider to integrate with Laravel’s Auth:

    use Illuminate\Support\Facades\Auth;
    
    public function authenticate(TokenInterface $token)
    {
        $user = Auth::user(); // Custom logic
        return new OAuthUser($user, $token);
    }
    

Laravel-Specific Quirks

  • Service Container: Bind Symfony services to Laravel’s container in AppServiceProvider:

    public function register()
    {
        $this->app->singleton(
            \Cutwise\OAuthServerBundle\Model\TokenManagerInterface::class,
            \Cutwise\OAuthServerBundle\Model\TokenManager::class
        );
    }
    
  • Routing: Use Laravel’s Route::prefix('oauth') to namespace OAuth routes:

    Route::prefix('oauth')->group(function () {
        Route::post('/token', 'OAuthController@issueToken');
    });
    
  • Logging: Enable monolog for OAuth events:

    # config/packages/monolog.yaml
    handlers:
        oauth:
            type: stream
            path: "%kernel.logs_dir%/oauth.log"
            level: debug
            channels: ["oauth"]
    

    Add channel in config/packages/cutwise_oauth_server.yaml:

    logging: true
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui