Weave 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 5 Laravel Laravel Package

oriceon/oauth-5-laravel

Laravel wrapper for the OAuth 5 library that simplifies OAuth 1 and OAuth 2 authentication, enabling social login and API authorization with popular providers through a clean, configurable integration. It supports token management and provider-specific configuration.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Install: composer require oriceon/oauth-5-laravel. On Laravel 5.5+ the OAuthServiceProvider and OAuth facade are auto-discovered; on older 5.x you must register them manually in config/app.php:

    'providers' => [Oriceon\OAuth5\OAuthServiceProvider::class],
    'aliases'   => ['OAuth' => Oriceon\OAuth5\Facades\OAuth::class],
    
  2. Publish config: php artisan vendor:publish and open config/oauth-5-laravel.php. Each provider is a top-level key (facebook, google, twitter, github, linkedin, …) with client_id, client_secret, scope, and (usually) redirect_uri.

  3. Set credentials in .env and reference them from the config so secrets aren't committed. The redirect URI must exactly match what you registered with the provider — including trailing slashes.

  4. First use case — a simple "Login with Facebook": create two routes and one controller. Redirect route builds the authorization URL; callback route exchanges the code for a token and hits /me:

    Route::get('login/facebook', function () {
        return redirect((string) OAuth::consumer('Facebook')->getAuthorizationUri());
    });
    
    Route::get('login/facebook/callback', function () {
        $fb = OAuth::consumer('Facebook');
        $token = $fb->requestAccessToken(request('code'));
        $me = json_decode($fb->request('/me?fields=id,name,email'), true);
        // find-or-create the user, Auth::login(...)
        return redirect('/');
    });
    

    If that works end-to-end you understand the whole package: it is a thin Laravel DI wrapper around the Lusitanian PHPOAuthLib consumer library.

Implementation Patterns

Thin controller, fat service. The package only gives you a ServiceFactory and a facade. Wrap consumer creation, token exchange, and profile fetching in a dedicated SocialAuthService or per-provider classes; keep the raw OAuth::consumer() calls out of controllers. This makes it far easier to swap in a newer library later.

Two-step OAuth 2 flow (the common path).

// Step 1
$service = OAuth::consumer('Google', $callbackUrl);
return redirect((string) $service->getAuthorizationUri());

// Step 2 (callback)
$service = OAuth::consumer('Google', $callbackUrl);
$token   = $service->requestAccessToken($code);
$data    = json_decode($service->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);

Pass the callback URL as the second argument when you need it to differ per environment or per tenant.

OAuth 1 flow (Twitter, older APIs). Three steps, and the request token must survive between the redirect and the callback:

$tw = OAuth::consumer('Twitter');
$reqToken = $tw->requestToken();                     // step 1
$tw->setToken($reqToken->getRequestToken(), $reqToken->getRequestTokenSecret());
return redirect((string) $tw->getAuthorizationUri()); // step 2

// callback
$tw = OAuth::consumer('Twitter');
$tw->setToken($requestToken, $requestTokenSecret);  // restore from session/DB
$token = $tw->requestAccessToken(request('oauth_token'), request('oauth_verifier'));

Token persistence. The library returns OAuth\Common\Token\TokenInterface objects, not arrays. They are not JSON-serializable in a useful way — serialize() them and store in the session, cache, or a social_tokens table:

session(['oauth_token' => serialize($token)]);
// later
$token = unserialize(session('oauth_token'));
$service->setAccessToken($token); // or pass into requestAccessToken()

Store access_token, refresh_token, endPoint, and expires — the library uses getEndOfLife() to decide whether to refresh.

Multi-provider users. Keep a social_accounts table (user_id, provider, provider_uid, token). Route all providers through one controller and resolve the consumer name from the route segment. This avoids duplicating five near-identical callback actions.

Integration tips.

  • Put both routes in the web middleware group so sessions work.
  • For OAuth 1 callbacks, the provider sends oauth_token and oauth_verifier as query params — use request() not Input::all() if you're on modern Laravel.
  • When a token is expired, $service->request(...) throws; wrap in try/catch and re-run the authorization flow or call the provider's refresh endpoint with the stored refresh_token.
  • Extend OAuth\ServiceFactory (or subclass a provider class) if you need a provider the config doesn't ship with; register it via a custom consumer callback or by editing the factory mapping.

Gotchas and Tips

The package is essentially unmaintained. This fork mainly kept it working across Laravel 5–6. Do not build a new project on it; instead consider league/oauth2-client + socialiteproviders/*. If you're stuck on it, isolate it behind an interface so you can replace it.

Config cache bites. If you add a provider to config/oauth-5-laravel.php and it "doesn't exist," you forgot php artisan config:clear. The facade reads whatever is cached.

redirect_uri must be absolute and identical. Relative URIs, http vs https, www vs bare domain, and extra trailing slashes all cause redirect_uri_mismatch from the provider — this is the most common support ticket. Set the callback in the config explicitly and never let it be inferred.

No CSRF/state validation by default. getAuthorizationUri() does not add a state parameter. For OAuth 2 you should append one yourself and verify it on return, otherwise the login flow is open to CSRF account-linking. Append with ->getAuthorizationUri(['state' => $nonce]) and compare against the session value.

Token objects are finicky. setAccessToken() expects the token object, not the raw string. If you persist only strings, reconstruct with new \OAuth\Common\Token\StdOAuth2Token() and setAccessToken($string) / setRefreshToken(...). Forgetting setEndOfLife means refresh logic silently never triggers.

Errors are exceptions, not return codes. requestAccessToken() throws OAuth\Common\Http\Exception\TokenResponseException on bad codes and OAuth\Common\Exception\Exception subclasses elsewhere. Catch these and redirect to a friendly error page — otherwise users hitting back-button replays of a consumed code see a 500.

Scopes live in config, not in code. Changing scopes at runtime requires passing an array as the third argument to OAuth::consumer($name, $callback, $scope). Google in particular will silently drop requested scopes if you don't pass a full set — re-request the token after any scope change, or the previously granted token won't include the new scope.

Facebook/Google API versions drift. The package hard-codes endpoints like /me and /oauth2/v1/userinfo. These still work, but the fields returned (e.g. email) depend on the provider's current API version and the user's privacy settings. Never assume email is present — handle its absence when creating local users.

Debugging tip: log (string) $service->getAuthorizationUri() and the exact redirect_uri the provider sees (they differ if config cache is stale). On the callback, log the full request query string before exchanging the code — most failures are wrong code, wrong state, or a redirected-to http URL that lost the session.

Extension point: OAuth::consumer() accepts a custom ServiceFactory via a setter on the provider; that's the cleanest way to add a new provider without forking the package.

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.
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource