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 Server Httpfoundation Bridge Laravel Package

bshaffer/oauth2-server-httpfoundation-bridge

Symfony HttpFoundation bridge for bshaffer/oauth2-server, enabling OAuth2 requests and responses to work seamlessly with Symfony/Laravel HttpFoundation objects. Provides adapters to integrate the OAuth2 server with HttpFoundation-based apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package:

    composer require bshaffer/oauth2-server-httpfoundation-bridge
    

    Ensure version matches oauth2-server-php (e.g., ^1.7 for Laravel 10).

  2. Basic Integration: In your OAuth2 controller (e.g., app/Http/Controllers/OAuth2Controller.php):

    use OAuth2\HttpFoundationBridge\Request as BridgeRequest;
    use OAuth2\HttpFoundationBridge\Response as BridgeResponse;
    use OAuth2\Server;
    
    public function token(Request $request) {
        $oauthRequest = BridgeRequest::createFromGlobals();
        $oauthResponse = new BridgeResponse();
        $server = new Server($storage, $tokenStorage, $scopeStorage);
    
        return $server->handleTokenRequest($oauthRequest, $oauthResponse);
    }
    
  3. Route Definition:

    Route::post('/oauth/token', [OAuth2Controller::class, 'token']);
    

First Use Case

Token Endpoint: Replace manual parsing of grant_type, client_id, etc., with the bridge’s BridgeRequest:

// Before (manual parsing)
$grantType = $_POST['grant_type'] ?? null;

// After (bridge handles it)
$grantType = $oauthRequest->getGrantType();

Implementation Patterns

Core Workflows

1. Request Handling

  • Global Requests: Use BridgeRequest::createFromGlobals() for CLI or PSR-7 environments (e.g., Laravel’s Request object).

    $request = BridgeRequest::createFromGlobals();
    $server->validateAuthorizationCodeGrantType($request);
    
  • Existing Request Objects: Convert Laravel’s Illuminate\Http\Request to OAuth2-compatible:

    $bridgeRequest = BridgeRequest::createFromRequest($request);
    
  • Request Stack (Laravel 5.5+): For middleware or service containers:

    $bridgeRequest = BridgeRequest::createFromRequestStack();
    

2. Response Handling

  • JSON Responses: The BridgeResponse extends Symfony\Component\HttpFoundation\JsonResponse, so it works seamlessly with Laravel’s JSON middleware:

    $response = new BridgeResponse();
    $server->handleTokenRequest($request, $response);
    return $response; // Laravel’s JSON middleware auto-converts
    
  • Custom Responses: Extend BridgeResponse for non-JSON formats (e.g., HTML for error pages):

    class CustomResponse extends BridgeResponse {
        public function setHttpCode($code) {
            $this->setStatusCode($code);
        }
    }
    

3. Middleware Integration

Wrap OAuth2 logic in Laravel middleware for global handling:

// app/Http/Middleware/OAuth2Bridge.php
public function handle($request, Closure $next) {
    $oauthRequest = BridgeRequest::createFromRequest($request);
    $response = $next($request);

    if ($response instanceof BridgeResponse) {
        return $response;
    }
    return $response;
}

Register in app/Http/Kernel.php:

protected $middleware = [
    \App\Http\Middleware\OAuth2Bridge::class,
];

4. Testing

Use HttpFoundation objects directly in tests:

public function testTokenRequest() {
    $request = new Request([], [], [
        'grant_type' => 'client_credentials',
        'client_id' => 'test_client',
        'client_secret' => 'secret',
    ]);
    $bridgeRequest = BridgeRequest::createFromRequest($request);
    $response = $this->server->handleTokenRequest($bridgeRequest, new BridgeResponse());

    $this->assertEquals(200, $response->getStatusCode());
}

Integration Tips

  • Laravel Service Container: Bind the bridge to the container for dependency injection:

    $app->bind('oauth2.bridge.request', function () {
        return BridgeRequest::createFromGlobals();
    });
    
  • Validation: Combine with Laravel’s validation (e.g., Validator facade) before OAuth2 processing:

    $validator = Validator::make($request->all(), [
        'grant_type' => 'required|in:authorization_code,client_credentials',
    ]);
    if ($validator->fails()) {
        return response()->json(['error' => 'invalid_request'], 400);
    }
    
  • Error Handling: Catch OAuth2 exceptions and convert to Laravel responses:

    try {
        $server->handleTokenRequest($request, $response);
    } catch (\OAuth2\ServerException $e) {
        return response()->json([
            'error' => $e->getMessage(),
            'error_description' => $e->getErrorDescription(),
        ], $e->getHttpCode());
    }
    
  • CORS: Use Laravel’s CORS middleware alongside OAuth2 to ensure preflight requests are handled:

    Route::middleware(['cors'])->post('/oauth/token', ...);
    

Gotchas and Tips

Pitfalls

  1. Version Mismatches:

    • Symfony Components: The bridge requires specific versions of symfony/http-foundation. For Laravel 10 (Symfony 6.4), use ^1.7:
      "bshaffer/oauth2-server-httpfoundation-bridge": "^1.7"
      
    • OAuth2 Server: Always match the bridge version with oauth2-server-php (e.g., ^1.7 for both).
  2. Request Order:

    • Middleware Conflicts: If other middleware modifies $_GET/$_POST before the bridge processes the request, OAuth2 parameters may be lost. Ensure the bridge middleware runs first in the stack.
  3. Response Types:

    • The BridgeResponse always returns JSON. For non-JSON responses (e.g., HTML), create a custom class extending BridgeResponse and override setHttpCode()/setContent().
  4. PHP Warnings:

    • Older PHP versions (e.g., 7.1) may trigger warnings with Symfony 4+. Use PHP 7.4+ to avoid:
      PHP Warning:  Parameter 2 to OAuth2\HttpFoundationBridge\Request::__construct() has a default value followed by a required parameter
      
      Fix: Upgrade PHP or pin to ^1.6 of the bridge.
  5. Global State:

    • createFromGlobals() relies on $_SERVER, $_GET, etc. In tests or non-web contexts, use createFromRequest() instead.
  6. CSRF Protection:

    • Laravel’s CSRF middleware may block OAuth2 requests (e.g., /oauth/token). Exclude the route:
      Route::post('/oauth/token', ...)->middleware('throttle', 'bindings')->withoutMiddleware('csrf');
      

Debugging Tips

  1. Request Inspection: Dump the bridge request to verify parameter parsing:

    dd($oauthRequest->getRequestParameters());
    
  2. Response Validation: Check the raw response content:

    $response = $server->handleTokenRequest($request, $bridgeResponse);
    dd($response->getContent());
    
  3. Error Codes: OAuth2 errors map to HTTP codes (e.g., 400 for invalid_request). Use Laravel’s abort() helper for consistency:

    if ($oauthRequest->getError()) {
        abort($response->getStatusCode(), $response->getContent());
    }
    
  4. Logging: Log OAuth2 events for auditing:

    \Log::info('OAuth2 Token Request', [
        'grant_type' => $oauthRequest->getGrantType(),
        'client_id' => $oauthRequest->getClientId(),
    ]);
    

Extension Points

  1. Custom Storage: Extend oauth2-server-php’s storage classes (e.g., Client, AccessToken) and reuse them with the bridge.

  2. Grant Types: Add custom grant types by extending OAuth2\GrantType\AbstractGrant and register them with the server:

    $server->addGrantType(new CustomGrant($storage));
    
  3. Response Formatters: Override BridgeResponse to support custom formats (e.g., XML):

    class XmlResponse extends BridgeResponse {
        public function setContent($content) {
            $this->setContent(simplexml_load_string($content));
        }
    }
    
  4. Middleware Chaining: Chain multiple OAuth2 middlewares for layered validation:

    $middleware->push(\App\Http\Middleware\ValidateClient::class);
    $middleware->push(\App\Http\Middleware\CheckScopes::class);
    

Performance Quirks

  1. Request Parsing: The bridge parses $_GET/$_POST on instantiation. For high-tra
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor