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

averor/oauth-server-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require averor/oauth-server-bundle
    

    Add to config/bundles.php (Symfony):

    return [
        // ...
        Averor\OAuthServerBundle\AverorOAuthServerBundle::class => ['all' => true],
    ];
    
  2. Configuration Define OAuth endpoints in config/packages/averor_oauth_server.yaml:

    averor_oauth_server:
        token_endpoint: /oauth/token
        authorize_endpoint: /oauth/authorize
        client_class: App\Entity\OAuthClient
        access_token_class: App\Entity\AccessToken
        refresh_token_class: App\Entity\RefreshToken
        auth_code_class: App\Entity\AuthCode
    
  3. First Use Case Create a client entity (e.g., OAuthClient) with required fields:

    // src/Entity/OAuthClient.php
    use Averor\OAuthServerBundle\Entity\ClientInterface;
    
    class OAuthClient implements ClientInterface {
        // Required fields: id, secret, redirectUri, name
    }
    

    Register the entity as a Doctrine resource and clear cache:

    php bin/console doctrine:schema:update --force
    
  4. Test the Token Endpoint Use curl to request a token:

    curl -X POST \
      -H "Content-Type: application/x-www-form-urlencoded" \
      -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \
      http://your-app/oauth/token
    

Implementation Patterns

Workflows

1. Client Credentials Flow

  • Use Case: Server-to-server authentication (e.g., microservices).
  • Implementation:
    $client = $this->getDoctrine()->getRepository(OAuthClient::class)->find('client_id');
    $token = $this->oauthServer->getAccessToken($client, 'client_credentials');
    
  • Response Handling:
    $tokenData = json_decode($token->jsonSerialize(), true);
    $accessToken = $tokenData['access_token'];
    

2. Authorization Code Flow

  • Use Case: Web/mobile apps (redirect-based auth).
  • Steps:
    1. Redirect user to /oauth/authorize with response_type=code.
    2. Exchange code for token:
      $authCode = $this->oauthServer->getAuthCodeRepository()->find($code);
      $token = $this->oauthServer->getAccessToken($authCode->getClient(), 'authorization_code', [
          'code' => $code,
          'redirect_uri' => $authCode->getRedirectUri(),
      ]);
      

3. Resource Owner Password Flow

  • Use Case: Trusted clients (e.g., internal tools).
  • Implementation:
    $user = $this->getUser(); // Symfony UserInterface
    $client = $this->getDoctrine()->getRepository(OAuthClient::class)->find('client_id');
    $token = $this->oauthServer->getAccessToken($client, 'password', [
        'username' => $user->getUsername(),
        'password' => $password,
    ]);
    

Integration Tips

Symfony Security Integration

  • Use the bundle’s OAuthTokenAuthenticator to validate access tokens:
    # config/packages/security.yaml
    firewalls:
        main:
            stateless: true
            provider: oauth_token
            custom_authenticators:
                - Averor\OAuthServerBundle\Security\OAuthTokenAuthenticator
    providers:
        oauth_token:
            entity:
                class: App\Entity\User
                property: oauthId
    

Custom Scopes

  • Extend the Scope entity or use a trait:
    use Averor\OAuthServerBundle\Entity\ScopeInterface;
    
    class CustomScope implements ScopeInterface {
        public function getIdentifier(): string { return 'custom_scope'; }
    }
    
  • Register scopes in config:
    averor_oauth_server:
        scopes:
            - { identifier: 'read', description: 'Read access' }
            - { identifier: 'write', description: 'Write access' }
    

Custom Grant Types

  • Implement GrantTypeInterface:
    use Averor\OAuthServerBundle\Grant\GrantTypeInterface;
    
    class CustomGrant implements GrantTypeInterface {
        public function getIdentifier(): string { return 'custom'; }
        public function validate(array $params, ClientInterface $client): bool { /* ... */ }
        public function generateToken(array $params, ClientInterface $client): AccessTokenInterface { /* ... */ }
    }
    
  • Register in services:
    services:
        App\Grant\CustomGrant:
            tags: [averor_oauth_server.grant_type]
    

Gotchas and Tips

Pitfalls

1. Missing Doctrine Entities

  • Error: Class [App\Entity\AccessToken] does not exist.
  • Fix: Ensure all required entities (Client, AccessToken, RefreshToken, AuthCode) are:
    • Implemented from their respective interfaces (ClientInterface, AccessTokenInterface, etc.).
    • Mapped as Doctrine entities with proper fields (e.g., id, client_id, expiresAt).
  • Debug: Run php bin/console debug:container averor_oauth_server to verify service binding.

2. Incorrect Redirect URIs

  • Error: redirect_uri_mismatch during authorization.
  • Fix:
    • Ensure redirect_uri in the authorize request matches the client’s registered URI.
    • Use absolute URIs (e.g., https://example.com/callback).
  • Config: Set require_redirect_uri_registration in averor_oauth_server.yaml:
    averor_oauth_server:
        require_redirect_uri_registration: true
    

3. Token Expiration

  • Issue: Tokens expire too quickly or not at all.
  • Fix:
    • Set access_token_lifetime and refresh_token_lifetime in config (default: 3600/2592000 seconds):
      averor_oauth_server:
          access_token_lifetime: 7200 # 2 hours
          refresh_token_lifetime: 2592000 # 30 days
      
    • For custom logic, override getLifetime() in your AccessToken entity.

4. CSRF Protection

  • Issue: state parameter not validated in authorize flow.
  • Fix: Enable CSRF protection in config:
    averor_oauth_server:
        authorize:
            enable_csrf: true
    
  • Note: Requires state parameter in authorize requests.

5. Scope Validation

  • Issue: Scopes are ignored or not enforced.
  • Fix:
    • Ensure scopes are defined in the database or config.
    • Validate scopes in your AccessToken entity’s getScopes() method.
    • Use scope parameter in token requests (e.g., scope=read write).

Debugging Tips

Enable Verbose Logging

averor_oauth_server:
    debug: true

Logs will appear in var/log/dev.log.

Dump Request/Response

Use Symfony’s Dumper in a controller:

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$request = Request::createFromGlobals();
dump($request->query->all(), $request->request->all());

Test with Postman

  • Authorize Request:
    GET http://your-app/oauth/authorize?
        response_type=code&
        client_id=CLIENT_ID&
        redirect_uri=REDIRECT_URI&
        scope=read&
        state=random_state
    
  • Token Request:
    POST http://your-app/oauth/token
    Body: grant_type=authorization_code&code=AUTH_CODE&redirect_uri=REDIRECT_URI&client_id=CLIENT_ID&client_secret=CLIENT_SECRET
    

Extension Points

Custom Storage Backends

  • Implement StorageInterface for non-Doctrine storage (e.g., Redis):
    use Averor\OAuthServerBundle\Storage\StorageInterface;
    
    class RedisStorage implements StorageInterface {
        public function findClient($clientId) { /* ... */ }
        public function findAccessToken($token) { /* ... */ }
        // ... other methods
    }
    
  • Register as a service:
    services:
        App\Storage\RedisStorage:
            tags: [averor_oauth_server.storage]
    

Event Listeners

  • Listen to OAuth events (e.g., token generation):
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