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

jacobkiers/oauth

OAuth 1 PHP library based on Andy Smith’s original implementation, forked via EHER. Includes request token support (reported working), with other flows not fully tested yet. Travis CI-enabled; suitable for experimenting with OAuth 1 signing and requests.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require jacobkiers/oauth
    

    Ensure your composer.json includes:

    "require": {
        "jacobkiers/oauth": "^1.0"
    }
    
  2. Basic Initialization Create a service class to wrap the OAuth client (e.g., app/Services/OAuthService.php):

    namespace App\Services;
    
    use OAuth\OAuth1\Service\Consumer;
    use OAuth\OAuth1\Token\Token;
    
    class OAuthService extends Consumer
    {
        public function __construct(string $consumerKey, string $consumerSecret, string $callbackUrl)
        {
            parent::__construct($consumerKey, $consumerSecret, $callbackUrl);
        }
    
        public function getRequestToken(): Token
        {
            return $this->getRequestToken();
        }
    
        public function getAccessToken(Token $requestToken, string $verifier): Token
        {
            return $this->getAccessToken($requestToken, $verifier);
        }
    }
    
  3. First Use Case: Request Token Register the service in AppServiceProvider:

    public function register()
    {
        $this->app->singleton('oauth', function ($app) {
            return new OAuthService(
                config('services.twitter.key'),
                config('services.twitter.secret'),
                url('/oauth/callback')
            );
        });
    }
    

    Use it in a controller:

    use Illuminate\Support\Facades\Redirect;
    
    public function requestToken()
    {
        $token = app('oauth')->getRequestToken();
        session(['oauth_token' => $token->key, 'oauth_token_secret' => $token->secret]);
        return Redirect::to($token->getAuthorizationUrl());
    }
    

Implementation Patterns

Workflow: OAuth 1.0a Flow in Laravel

  1. Request Token and Redirect

    public function requestToken()
    {
        $oauth = app('oauth');
        $token = $oauth->getRequestToken();
        session(['oauth_token' => $token->key, 'oauth_token_secret' => $token->secret]);
        return Redirect::to($token->getAuthorizationUrl());
    }
    
  2. Handle Callback

    public function handleCallback(Request $request)
    {
        $oauth = app('oauth');
        $token = new Token(
            session('oauth_token'),
            session('oauth_token_secret')
        );
        $accessToken = $oauth->getAccessToken($token, $request->oauth_verifier);
        session(['access_token' => $accessToken->key, 'access_token_secret' => $accessToken->secret]);
        return redirect('/dashboard');
    }
    
  3. Protected API Requests

    public function fetchProtectedData()
    {
        $oauth = app('oauth');
        $token = new Token(
            session('access_token'),
            session('access_token_secret')
        );
        $response = $oauth->request('/protected/resource', $token, 'GET');
        return json_decode($response->getBody(), true);
    }
    

Integration Tips

  • Middleware for Token Management Create middleware to attach tokens to requests:

    namespace App\Http\Middleware;
    
    use Closure;
    use OAuth\OAuth1\Token\Token;
    
    class OAuthTokenMiddleware
    {
        public function handle($request, Closure $next)
        {
            if ($request->has('oauth_token') && $request->has('oauth_token_secret')) {
                $request->merge([
                    'oauth_token' => new Token(
                        $request->oauth_token,
                        $request->oauth_token_secret
                    )
                ]);
            }
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        // ...
        \App\Http\Middleware\OAuthTokenMiddleware::class,
    ];
    
  • Database Storage Use Eloquent models to persist tokens:

    // Migration
    Schema::create('oauth_tokens', function (Blueprint $table) {
        $table->id();
        $table->string('token');
        $table->string('token_secret');
        $table->string('user_id')->nullable();
        $table->timestamps();
    });
    
    // Model
    class OAuthToken extends Model
    {
        protected $fillable = ['token', 'token_secret', 'user_id'];
    }
    
  • Configuration Store credentials in config/services.php:

    'twitter' => [
        'key' => env('TWITTER_KEY'),
        'secret' => env('TWITTER_SECRET'),
    ],
    

Gotchas and Tips

Pitfalls

  1. Session Management

    • The package relies on raw $_GET/$_POST data. Laravel’s Request object may require manual parsing for OAuth parameters.
    • Fix: Use middleware to inject tokens into the request object.
  2. PHP Version Incompatibility

    • The package lacks PHP 8.x support (no type hints, deprecated functions).
    • Fix: Downgrade to PHP 7.4 or patch the library manually (e.g., add strict_types=1).
  3. No Built-in CSRF Protection

    • OAuth 1.0a is vulnerable to CSRF if not handled carefully.
    • Fix: Use Laravel’s VerifyCsrfToken middleware alongside OAuth flows.
  4. Token Storage

    • The package doesn’t handle token persistence. Tokens expire or may need revocation.
    • Fix: Store tokens in the database and implement a cleanup mechanism.
  5. Error Handling

    • The package throws generic exceptions. Laravel’s exception handling may not catch OAuth-specific errors.
    • Fix: Wrap OAuth calls in try-catch blocks and log errors:
      try {
          $token = $oauth->getRequestToken();
      } catch (\Exception $e) {
          Log::error("OAuth Error: " . $e->getMessage());
          abort(500, "OAuth request failed");
      }
      

Debugging Tips

  • Enable Verbose Logging Configure the OAuth client to log requests/responses:

    $oauth = new OAuthService($key, $secret, $callbackUrl);
    $oauth->setDebug(true); // Enable debug mode
    
  • Inspect Raw Requests Use Laravel’s tap to debug HTTP requests:

    $response = $oauth->request('/endpoint', $token, 'GET')->tap(function ($response) {
        Log::debug("Response: " . $response->getBody());
    });
    
  • Test with a Mock Provider Use a local OAuth 1.0a test server (e.g., oauth-1.0a-server) to avoid rate limits or API changes.

Extension Points

  1. Custom Signature Methods Extend the OAuth\OAuth1\Token\SignatureMethod class to support additional algorithms:

    class CustomSignatureMethod extends \OAuth\OAuth1\Token\SignatureMethod\HMAC_SHA1
    {
        public function sign($data, $key)
        {
            // Custom logic
        }
    }
    
  2. Laravel Facade Create a facade for cleaner syntax:

    // app/OAuth.php
    namespace App;
    
    use Illuminate\Support\Facades\Facade;
    
    class OAuth extends Facade
    {
        protected static function getFacadeAccessor() { return 'oauth'; }
    }
    

    Usage:

    $token = OAuth::getRequestToken();
    
  3. Event Listeners Dispatch events for OAuth flow steps (e.g., OAuthTokenRequested, OAuthTokenExchanged):

    event(new OAuthTokenRequested($token));
    

Configuration Quirks

  • cURL Options The package uses curl_setopt directly. Laravel’s Http client may override these. Ensure compatibility:

    $oauth->setCurlOptions([
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
    ]);
    
  • URL Encoding The package may not handle URL encoding consistently. Use Laravel’s Str::of($url)->urlencode() for safety.

  • Timeouts Set reasonable timeouts to avoid hanging requests:

    $oauth->setCurlOptions([
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CONNECTTIMEOUT => 10,
    ]);
    
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