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

akeneo/oauth-server-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

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

Add to config/bundles.php:

return [
    // ...
    Akeneo\OAuthServerBundle\AkeneoOAuthServerBundle::class => ['all' => true],
];
  1. Configure OAuth2 Server Update config/packages/oauth_server.yaml (auto-generated after installation):

    oauth_server:
        db_driver: orm          # or 'mongodb', 'propel', etc.
        client_class:          # Custom client entity (optional)
            App\Entity\OAuthClient
        access_token_class:    # Custom access token entity (optional)
            App\Entity\OAuthAccessToken
        refresh_token_class:   # Custom refresh token entity (optional)
            App\Entity\OAuthRefreshToken
        auth_code_class:       # Custom auth code entity (optional)
            App\Entity\OAuthAuthCode
        service:
            user_provider:     # Link to your user provider (e.g., FOSUserBundle)
                id: fos_user.user_provider.username_email
    
  2. First Use Case: Protect an API Endpoint Annotate a controller method with @OAuth:

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
    
    class ApiController extends AbstractController
    {
        /**
         * @Security("is_granted('IS_AUTHENTICATED_FULLY')")
         */
        public function secureEndpoint()
        {
            return $this->json(['data' => 'protected']);
        }
    }
    
  3. Generate Clients Use the fos:oauth-server:create-client command:

    php bin/console fos:oauth-server:create-client
    

    (Follow prompts to set random_id, secret, redirect_uri, etc.)


Implementation Patterns

Common Workflows

  1. Token Management

    • Issue Tokens: Use the fos_oauth_server.token route with POST:
      curl -X POST -d 'grant_type=password&username=user&password=pass' http://your-app.com/oauth/v2/token
      
    • Refresh Tokens: Replace grant_type with refresh_token and include the refresh token.
    • Revoke Tokens: Use the fos_oauth_server.revoke_token route:
      curl -X POST -d 'token=ACCESS_TOKEN' http://your-app.com/oauth/v2/revoke_token
      
  2. Custom User Providers Extend the default provider to integrate with your user system:

    // src/Service/CustomUserProvider.php
    use Symfony\Component\Security\Core\User\UserProviderInterface;
    
    class CustomUserProvider implements UserProviderInterface
    {
        public function loadUserByUsername($username)
        {
            // Fetch user from your DB/API
            return new User(); // Your user entity
        }
        // ... other required methods
    }
    

    Register in config/services.yaml:

    services:
        App\Service\CustomUserProvider:
            tags: ['oauth.user_provider']
    
  3. Scopes and Roles Define scopes in the client configuration (e.g., read, write):

    # config/packages/oauth_server.yaml
    oauth_server:
        service:
            client_class: App\Entity\OAuthClient
    

    In your OAuthClient entity:

    // src/Entity/OAuthClient.php
    public function getAllowedScopes()
    {
        return ['read', 'write']; // Scopes for this client
    }
    

    Enforce scopes in controllers:

    /**
     * @Security("is_granted('ROLE_OAUTH_SCOPE_read')")
     */
    public function readData()
    {
        // ...
    }
    
  4. Integration with FOSUserBundle If using FOSUserBundle, configure the user provider in oauth_server.yaml:

    oauth_server:
        service:
            user_provider: fos_user.user_provider.username_email
    

    Ensure your User entity implements OAuthAwareInterface:

    use Akeneo\OAuthServerBundle\Model\OAuthAwareInterface;
    
    class User implements OAuthAwareInterface
    {
        // ...
    }
    
  5. Customizing Token Entities Extend default entities (e.g., OAuthAccessToken) to add custom fields:

    // src/Entity/OAuthAccessToken.php
    use Akeneo\OAuthServerBundle\Entity\OAuthAccessToken as BaseToken;
    
    class OAuthAccessToken extends BaseToken
    {
        /**
         * @ORM\Column(type="string", nullable=true)
         */
        private $customField;
    
        // Getters/setters
    }
    

    Update oauth_server.yaml to reference your custom class.


Integration Tips

  • Symfony Security Integration Use the oauth_token firewall in config/packages/security.yaml:

    security:
        firewalls:
            api:
                pattern: ^/api
                oauth_token:
                    check_path: /oauth/v2/token
                    services:
                        - App\Service\CustomUserProvider
    
  • Testing Tokens Use the fos:oauth-server:create-token command for testing:

    php bin/console fos:oauth-server:create-token --client-id=CLIENT_ID --username=USERNAME
    
  • Rate Limiting Combine with Symfony’s rate_limiter to protect token endpoints:

    # config/packages/security.yaml
    firewalls:
        oauth_token:
            rate_limiter: oauth_token_limiter
    
  • Logging Enable OAuth logging in config/packages/monolog.yaml:

    handlers:
        oauth:
            type: stream
            path: "%kernel.logs_dir%/oauth.log"
            level: debug
            channels: ["oauth"]
    

Gotchas and Tips

Pitfalls

  1. Database Schema Mismatches

    • If using custom entities, ensure your database schema matches the entity definitions. Run migrations after changes:
      php bin/console doctrine:migrations:diff
      php bin/console doctrine:migrations:migrate
      
    • Fix: Drop and recreate the database if migrations fail.
  2. CORS Issues

    • The /oauth/v2/token endpoint may block requests from certain origins. Configure CORS in your frontend or backend:
      # config/packages/nelmio_cors.yaml
      nelmio_cors:
          defaults:
              allow_origin: ["*"]
              allow_methods: ["POST"]
              allow_headers: ["Authorization", "Content-Type"]
              expose_headers: ["Authorization"]
      
  3. Token Expiry Quirks

    • Default token expiry is 3600 seconds (1 hour). Adjust in config/packages/oauth_server.yaml:
      oauth_server:
          service:
              access_token_lifetime: 7200 # 2 hours
              refresh_token_lifetime: 1209600 # 2 weeks
      
    • Tip: Use refresh_token_lifetime to allow long-lived sessions with refreshable tokens.
  4. Client Secret Management

    • Hardcoding secrets in config is insecure. Use environment variables:
      # .env
      OAUTH_CLIENT_SECRET=your_secret_here
      
      # config/packages/oauth_server.yaml
      oauth_server:
          service:
              client_class: App\Entity\OAuthClient
              client_secret: "%env(OAUTH_CLIENT_SECRET)%"
      
  5. User Provider Conflicts

    • If using multiple user providers (e.g., FOSUserBundle + custom), ensure the OAuth bundle’s provider is prioritized:
      oauth_server:
          service:
              user_provider: your_custom_provider_id
      
  6. PKCE (Proof Key for Code Exchange)

    • Enable PKCE for mobile/native apps (requires grant_type=authorization_code):
      oauth_server:
          service:
              pkce_support: true
      
    • Note: PKCE requires additional frontend handling (e.g., generating code_verifier and code_challenge).

Debugging Tips

  1. Enable Debug Mode Set APP_DEBUG=1 in .env to see detailed OAuth errors in logs.

  2. Check Logs Monitor var/log/oauth.log for token generation/revocation issues.

  3. Validate Token Manually Use the fos:oauth-server:validate-token command:

    php bin/console fos:oauth-server:validate-token ACCESS_TOKEN
    
  4. Common Errors

    • invalid_grant: Wrong grant_type, username/password, or expired refresh token.
      • Fix: Verify credentials and token lifetimes.
    • unsupported_grant_type: Missing or incorrect grant_type in the request.
      • Fix: Ensure the request
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