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 Laravel Package

aescarcha/oauth

Symfony OAuth server bundle integrating FOSOAuthServer with FOSUser, FOSRest, JMS Serializer, and NelmioApiDoc. Provides routes and configuration to expose JSON-based API authentication and documentation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for First Use Case

  1. Installation Run these commands in order:

    composer require aescarcha/oauth "~1"
    composer require friendsofsymfony/rest-bundle jms/serializer-bundle nelmio/api-doc-bundle friendsofsymfony/user-bundle aescarcha/user-bundle friendsofsymfony/oauth-server-bundle
    
  2. Enable Bundles Add to app/AppKernel.php:

    new Aescarcha\OauthServerBundle\AescarchaOauthServerBundle(),
    
  3. Configure Database Run migrations for OAuth tables (check src/Aescarcha/OauthServerBundle/Resources/doc/index.md for specifics).

  4. First OAuth Flow Use the built-in /oauth/v2/auth endpoint to test token generation:

    curl -X POST -d "grant_type=password&client_id=your_client_id&client_secret=your_secret&username=user&password=pass" http://your-app/oauth/v2/token
    
  5. Verify API Docs Access /api/doc (NelmioApiDocBundle) to explore OAuth endpoints interactively.


Implementation Patterns

Common Workflows

  1. Client Registration

    • Use Aescarcha\OauthServerBundle\Entity\Client to manage OAuth clients.
    • Example registration via controller:
      $client = new Client();
      $client->setRandomId(true);
      $client->setRedirectUris(['https://yourapp.com/callback']);
      $em->persist($client);
      $em->flush();
      
  2. Token Management

    • Issue tokens via Aescarcha\OauthServerBundle\Security\Token\OAuthToken:
      $token = $this->get('oauth.server')->getTokenStorage()->createAccessToken($client, $user, $scope);
      
  3. Resource Server Integration

    • Protect routes with annotations:
      use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
      /**
       * @Security("is_granted('IS_AUTHENTICATED_FULLY')")
       */
      public function secureAction()
      {
          // ...
      }
      
  4. Custom Scopes

    • Extend Aescarcha\OauthServerBundle\Entity\Scope for granular permissions:
      $scope = new Scope();
      $scope->setName('custom:admin');
      $scope->setDescription('Admin access');
      
  5. Refresh Tokens

    • Handle token refresh via Aescarcha\OauthServerBundle\Security\Token\RefreshToken:
      $refreshToken = $this->get('oauth.server')->getTokenStorage()->createRefreshToken($client, $user);
      

Integration Tips

  • Leverage FOSUserBundle Sync OAuth users with FOS\UserBundle\Model\User via Aescarcha\UserBundle.
  • API Documentation Use NelmioApiDocBundle to auto-generate OAuth flow docs (e.g., /api/doc#/OAuth2/token_post).
  • Testing Mock OAuthServer in PHPUnit:
    $this->container->set('oauth.server', $this->createMock(OAuthServer::class));
    

Gotchas and Tips

Pitfalls

  1. Bundle Dependencies

    • aescarcha/user-bundle is in dev-master; pin versions to avoid breaking changes:
      composer require aescarcha/user-bundle:dev-master@dev
      
    • Fix: Use composer why-not aescarcha/user-bundle to debug dependency conflicts.
  2. Token Storage

    • Default storage (doctrine:orm) may not persist tokens if not configured. Ensure:
      # config.yml
      aescarcha_oauth:
          storage: doctrine
      
  3. CORS Issues

    • friendsofsymfony/rest-bundle must be configured for OAuth callbacks:
      fos_rest:
          format_list:
              json: true
          param_format: json
      
  4. Scope Validation

    • Scopes are case-sensitive. Validate client-scopes match exactly:
      $client->setAllowedScopes(['read', 'write']);
      

Debugging Tips

  1. Enable OAuth Logging Add to config.yml:

    aescarcha_oauth:
        debug: true
    

    Logs appear in var/log/dev.log.

  2. Token Debugging Dump token data:

    $token = $this->get('oauth.server')->getTokenStorage()->findAccessToken($tokenValue);
    var_dump($token->getUser(), $token->getScopes());
    
  3. Common Errors

    • Invalid grant_type: Ensure grant_type matches the endpoint (e.g., password, authorization_code).
    • Client not found: Verify client_id and client_secret in the database.
    • User not found: Confirm FOS\UserBundle user provider is linked to OAuth.

Extension Points

  1. Custom Grant Types Extend Aescarcha\OauthServerBundle\Security\Token\GrantType\GrantTypeInterface:

    class CustomGrantType implements GrantTypeInterface {
        public function getName() { return 'custom'; }
        public function validate(array $params) { /* ... */ }
    }
    

    Register in services.yml:

    services:
        aescarcha_oauth.grant_type.custom:
            class: AppBundle\Security\Token\CustomGrantType
            tags:
                - { name: oauth.grant_type }
    
  2. Override Token Storage Bind a custom storage service:

    services:
        oauth.token_storage:
            class: AppBundle\Security\Token\CustomTokenStorage
            arguments: ['@doctrine.orm.entity_manager']
    
  3. API Response Customization Override Aescarcha\OauthServerBundle\EventListener\TokenResponseListener to modify token responses:

    public function onTokenResponse(GetResponseEvent $event) {
        $response = $event->getResponse();
        $response->headers->set('X-Custom-Header', 'value');
    }
    
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