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

Oauth2 Php Laravel Package

friendsofsymfony/oauth2-php

PHP OAuth2 library by FriendsOfSymfony providing client/server building blocks: token and authorization flows, grant types, access token handling, and extensible components for integrating OAuth2 authentication into Symfony and other PHP apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require friendsofsymfony/oauth2-php
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        FriendsOfSymfony\OAuth2ServerBundle\FriendsOfSymfonyOAuth2ServerBundle::class,
    ],
    
  2. Configuration Copy the default config to config/packages/friendsofsymfony_oauth2_server.yaml:

    php bin/console config:dump-reference friendsofsymfony_oauth2_server > config/packages/friendsofsymfony_oauth2_server.yaml
    

    Define your grant types, clients, and scopes in the config.

  3. First Use Case: Token Endpoint Test the /oauth/v2/token endpoint with a POST request:

    curl -X POST \
      -d "grant_type=password&client_id=your_client_id&client_secret=your_secret&username=user&password=pass" \
      http://your-app.test/oauth/v2/token
    

    Verify the response includes an access_token.


Key Files to Review

  • Config: config/packages/friendsofsymfony_oauth2_server.yaml (grants, clients, scopes).
  • Routes: config/routes/oauth2.yaml (default /oauth/v2/*).
  • Entities: src/Entity/ (customize Client, AccessToken, RefreshToken, etc.).
  • Services: src/Service/ (extend AuthorizationServer, ResourceOwnerPasswordTokenProvider, etc.).

Implementation Patterns

1. Grant Type Workflows

Password Grant (User Credentials)

// In a controller or service
$token = $this->oauth2->getToken('password', [
    'username' => 'user@example.com',
    'password' => 'securepassword',
    'client_id' => 'client_id',
    'client_secret' => 'client_secret',
]);

Use Case: Direct user authentication (e.g., mobile apps, trusted clients).

Client Credentials Grant (Machine-to-Machine)

$token = $this->oauth2->getToken('client_credentials', [
    'client_id'     => 'client_id',
    'client_secret' => 'client_secret',
    'scope'         => 'read write',
]);

Use Case: Background services or APIs calling other APIs.

Authorization Code Grant (Web Apps)

  1. Redirect user to /oauth/v2/auth?response_type=code&....
  2. Exchange code for token:
    $token = $this->oauth2->getToken('authorization_code', [
        'code'          => $request->input('code'),
        'redirect_uri'  => 'https://your-app.com/callback',
        'client_id'     => 'client_id',
        'client_secret' => 'client_secret',
    ]);
    

2. Customizing the Flow

Extend Token Providers

// src/Service/CustomTokenProvider.php
namespace App\Service;

use FriendsOfSymfony\OAuth2ServerBundle\Provider\TokenProviderInterface;
use FriendsOfSymfony\OAuth2ServerBundle\Model\ClientInterface;
use FriendsOfSymfony\OAuth2ServerBundle\Model\AccessTokenInterface;

class CustomTokenProvider implements TokenProviderInterface
{
    public function getToken(ClientInterface $client, array $params)
    {
        // Custom logic (e.g., validate API keys, add metadata to tokens)
        return new AccessToken($params['scope'], $client, 3600);
    }
}

Register in config/packages/friendsofsymfony_oauth2_server.yaml:

oauth2:
    token_providers:
        custom: App\Service\CustomTokenProvider

Add Custom Scopes

# config/packages/friendsofsymfony_oauth2_server.yaml
oauth2:
    scopes:
        custom_scope: "Access custom feature"

Use in requests:

curl -d "scope=custom_scope" ...

3. Middleware for Protected Routes

// src/Http/Middleware/OAuth2Middleware.php
namespace App\Http\Middleware;

use Closure;
use FriendsOfSymfony\OAuth2ServerBundle\Model\AccessTokenInterface;
use FriendsOfSymfony\OAuth2ServerBundle\OAuth2\OAuth2;

class OAuth2Middleware
{
    public function __construct(private OAuth2 $oauth2) {}

    public function handle($request, Closure $next)
    {
        $token = $this->oauth2->validateBearerToken($request->bearerToken());
        if (!$token) {
            abort(401, 'Invalid token');
        }
        // Attach token to request or user
        $request->merge(['oauth_token' => $token]);
        return $next($request);
    }
}

Register in app/Http/Kernel.php:

protected $routeMiddleware = [
    'auth.oauth' => \App\Http\Middleware\OAuth2Middleware::class,
];

Protect routes:

Route::middleware('auth.oauth')->get('/api/protected', ...);

4. Database Integration

Custom Entity Mappings

// src/Entity/Client.php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use FriendsOfSymfony\OAuth2ServerBundle\Entity\Client as BaseClient;

#[ORM\Entity]
class Client extends BaseClient
{
    #[ORM\Column(type: 'string', length: 255, nullable: true)]
    private ?string $apiKey;

    // Getters/setters...
}

Update config/packages/doctrine.yaml to point to your entities.


Gotchas and Tips

Pitfalls

  1. CSRF Protection

    • The authorization_code grant requires state and redirect_uri validation.
    • Fix: Use the built-in state parameter or implement CSRF tokens manually.
  2. Token Expiry

    • Default expiry is 1 hour for access tokens. Adjust in config:
      oauth2:
          access_token_ttl: 3600 # 1 hour in seconds
          refresh_token_ttl: 2592000 # 30 days
      
  3. Scope Validation

    • Scopes are case-sensitive. Ensure consistency in requests and config.
  4. Client Secrets in URLs

    • Avoid passing client_secret in URLs (e.g., redirect_uri). Use the PKCE flow for public clients:
      oauth2:
          grants:
              authorization_code:
                  pkce: true
      

Debugging Tips

  1. Enable Verbose Logging

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

    Add to config/packages/friendsofsymfony_oauth2_server.yaml:

    oauth2:
        debug: true
    
  2. Test with Postman

    • Use the Authorization tab to send Bearer tokens.
    • For authorization_code, simulate the redirect flow manually.
  3. Database Seeds Create a seeder to populate clients/scopes:

    // database/seeds/OAuth2Seeder.php
    use App\Entity\Client;
    use FriendsOfSymfony\OAuth2ServerBundle\Entity\Scope;
    
    public function run()
    {
        $client = new Client();
        $client->setRandomId();
        $client->setSecret('secret');
        $client->setRedirectUris(['https://example.com/callback']);
        $this->getEntityManager()->persist($client);
    
        $scope = new Scope();
        $scope->setKey('read');
        $scope->setDescription('Read access');
        $this->getEntityManager()->persist($scope);
    
        $this->getEntityManager()->flush();
    }
    

Extension Points

  1. Custom Grant Types Implement FriendsOfSymfony\OAuth2ServerBundle\Provider\GrantTypeProviderInterface:

    class CustomGrantProvider implements GrantTypeProviderInterface
    {
        public function getGrantType()
        {
            return 'custom_grant';
        }
    
        public function validate(array $params)
        {
            // Custom validation logic
            return ['access_token' => '...'];
        }
    }
    

    Register in config:

    oauth2:
        grants:
            custom_grant: App\Service\CustomGrantProvider
    
  2. Token Storage Extend FriendsOfSymfony\OAuth2ServerBundle\Entity\AccessToken to store additional metadata (e.g., IP, user agent):

    #[ORM\Column(type: 'string', length: 45, nullable: true)]
    private ?string $userAgent;
    
  3. Rate Limiting Use middleware to limit token requests:

    // src/Http/Middleware/RateLimitOAuth.php
    use Symfony\Component\Rate
    
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