PHPackages                             texhub/social-auth - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. texhub/social-auth

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

texhub/social-auth
==================

Simple, elegant social OAuth 2.0 login for any PHP framework with first-class Laravel support — Google &amp; GitHub out of the box, easily extensible.

v1.0.1(1mo ago)01MITPHPPHP ^8.2

Since Jun 1Pushed 1mo agoCompare

[ Source](https://github.com/TexhubPro/social-auth)[ Packagist](https://packagist.org/packages/texhub/social-auth)[ Docs](https://texhub.pro)[ RSS](/packages/texhub-social-auth/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (4)Versions (3)Used By (0)

TexHub · Social Auth
====================

[](#texhub--social-auth)

**English** · [Русский](README.ru.md)

[![License: MIT](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![PHP](https://camo.githubusercontent.com/d91d3d1139cf0d8faaa80eeeeac7d3c59c9319e56960ef81c948e4160be4c4c1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d3737376262342e737667)](composer.json)[![Laravel](https://camo.githubusercontent.com/3e9242504354dbb5afd360f9a1ec114126b2caddb73d9e789d9102c3285d2b05/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d3131253230253743253230313225323025374325323031332d6666326432302e737667)](#laravel)

Simple, elegant **social OAuth 2.0 login** for any PHP framework — **Google** &amp; **GitHub** out of the box, easily extensible — with first-class **Laravel** support.

---

Features
--------

[](#features)

- **OAuth 2.0 Authorization Code** flow done for you
- **Google** &amp; **GitHub** providers built in (GitHub falls back to the verified primary email)
- **Normalized `User`** — `id`, `nickname`, `name`, `email`, `avatar`, `token`, `raw`
- **CSRF state** helper, custom scopes &amp; extra params
- **Extensible** — add your own provider in a few lines
- Fully unit-tested (no network), pluggable HTTP transport

---

Installation
------------

[](#installation)

```
composer require texhub/social-auth
```

Requirements: **PHP ≥ 8.2** with `curl`, `json`.

---

Quick start
-----------

[](#quick-start)

```
use TexHub\SocialAuth\SocialAuth;

$social = SocialAuth::fromArray([
    'google' => [
        'client_id' => '...', 'client_secret' => '...',
        'redirect' => 'https://app.tj/auth/google/callback',
    ],
    'github' => [
        'client_id' => '...', 'client_secret' => '...',
        'redirect' => 'https://app.tj/auth/github/callback',
    ],
]);

// 1) Send the user to the provider (store the state in the session for CSRF):
$state = SocialAuth::generateState();
$_SESSION['oauth_state'] = $state;
header('Location: ' . $social->driver('google')->redirectUrl($state));

// 2) On your callback, verify state then get the user:
if (($_GET['state'] ?? null) !== ($_SESSION['oauth_state'] ?? null)) {
    exit('Invalid state');
}
$user = $social->driver('google')->userFromCode($_GET['code']);

$user->id;            // provider user id
$user->name;          // full name
$user->email;         // email
$user->avatar;        // avatar URL
$user->nickname;      // login/handle (GitHub)
$user->token->accessToken;   // OAuth access token
$user->token->refreshToken;  // when available (Google offline access)
```

---

Google / GitHub
---------------

[](#google--github)

Both work identically — just switch the driver name:

```
$social->driver('github')->redirectUrl($state);
$user = $social->driver('github')->userFromCode($code);
```

Default scopes: Google → `openid profile email`, GitHub → `read:user user:email`. Override per provider via `scopes`, and add provider params via `extra`(e.g. Google `['access_type' => 'offline', 'prompt' => 'consent']` for a refresh token).

---

Add your own provider
---------------------

[](#add-your-own-provider)

```
use TexHub\SocialAuth\Providers\AbstractProvider;
use TexHub\SocialAuth\User;

final class FacebookProvider extends AbstractProvider
{
    protected function authorizeUrl(): string { return 'https://www.facebook.com/v19.0/dialog/oauth'; }
    protected function tokenUrl(): string     { return 'https://graph.facebook.com/v19.0/oauth/access_token'; }
    protected function defaultScopes(): array { return ['email', 'public_profile']; }
    protected function fetchUser(string $token): array {
        return $this->get('https://graph.facebook.com/me?fields=id,name,email,picture', $token);
    }
    protected function mapUser(array $raw): User {
        return new User((string) $raw['id'], null, $raw['name'] ?? null, $raw['email'] ?? null,
            $raw['picture']['data']['url'] ?? null, $raw);
    }
}

$social->extend('facebook', FacebookProvider::class)
       ->configure('facebook', \TexHub\SocialAuth\ProviderConfig::fromArray($cfg));
```

---

Error handling
--------------

[](#error-handling)

```
use TexHub\SocialAuth\Exceptions\ApiException;
use TexHub\SocialAuth\Exceptions\ConfigurationException;

try {
    $user = $social->driver('google')->userFromCode($code);
} catch (ApiException $e) {
    // token exchange / profile error — $e->getMessage(), $e->httpStatus, $e->payload
} catch (ConfigurationException $e) {
    // unknown / unconfigured provider
}
```

---

 Laravel
-------------------------------------------

[](#-laravel)

Auto-discovered. Publish config:

```
php artisan vendor:publish --tag=social-auth-config
```

`.env`:

```
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...
GOOGLE_REDIRECT_URI=https://app.tj/auth/google/callback

GITHUB_CLIENT_ID=...
GITHUB_CLIENT_SECRET=...
GITHUB_REDIRECT_URI=https://app.tj/auth/github/callback
```

Controller:

```
use Illuminate\Http\Request;
use TexHub\SocialAuth\Laravel\SocialAuth;

public function redirect(string $provider, Request $request)
{
    $state = \TexHub\SocialAuth\SocialAuth::generateState();
    $request->session()->put('oauth_state', $state);

    return redirect()->away(SocialAuth::driver($provider)->redirectUrl($state));
}

public function callback(string $provider, Request $request)
{
    abort_unless($request->query('state') === $request->session()->pull('oauth_state'), 419);

    $user = SocialAuth::driver($provider)->userFromCode($request->query('code'));

    $account = User::updateOrCreate(
        ['provider' => $provider, 'provider_id' => $user->id],
        ['name' => $user->name, 'email' => $user->email, 'avatar' => $user->avatar],
    );
    auth()->login($account);

    return redirect('/dashboard');
}
```

Routes:

```
Route::get('/auth/{provider}', [AuthController::class, 'redirect']);
Route::get('/auth/{provider}/callback', [AuthController::class, 'callback']);
```

---

Testing
-------

[](#testing)

Inject a fake transport — no network needed:

```
use TexHub\SocialAuth\SocialAuth;
use TexHub\SocialAuth\Tests\Support\FakeTransport;

$t = (new FakeTransport())
    ->on('oauth2.googleapis.com/token', ['access_token' => 't', 'token_type' => 'Bearer'])
    ->on('userinfo', ['sub' => '1', 'email' => 'a@b.c', 'name' => 'A']);

$social = SocialAuth::fromArray($configs, $t);
$user = $social->driver('google')->userFromCode('code');
```

```
composer install && composer test
```

---

Architecture
------------

[](#architecture)

```
src/
├── SocialAuth.php           # manager / driver factory
├── ProviderConfig.php       # per-provider client id/secret/redirect/scopes
├── Token.php · User.php     # normalized value objects
├── Contracts/Provider.php   # provider interface
├── Providers/               # AbstractProvider, GoogleProvider, GitHubProvider
├── Http/                    # Transport, CurlTransport, RawResponse
├── Exceptions/              # ApiException, ConfigurationException, …
└── Laravel/                 # ServiceProvider + Facade

```

---

License
-------

[](#license)

MIT © TexHub Pro — built by Mahmudi Shodmehr.

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance93

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~19 days

Total

2

Last Release

34d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/217647751?v=4)[TexHub Pro](/maintainers/TexhubPro)[@TexhubPro](https://github.com/TexhubPro)

---

Top Contributors

[![TexhubPro](https://avatars.githubusercontent.com/u/217647751?v=4)](https://github.com/TexhubPro "TexhubPro (2 commits)")

---

Tags

githubgooglelaraveloauthoauth2phpsdksocial-loginphplaravelgoogleAuthenticationSSOoauthoauth2githubSocial Logintexhub

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/texhub-social-auth/health.svg)

```
[![Health](https://phpackages.com/badges/texhub-social-auth/health.svg)](https://phpackages.com/packages/texhub-social-auth)
```

###  Alternatives

[hwi/oauth-bundle

Support for authenticating users using both OAuth1.0a and OAuth2 in Symfony.

2.4k22.3M81](/packages/hwi-oauth-bundle)[and/oauth

Simple and amazing OAuth library with many providers. Just try it out!

4345.3k2](/packages/and-oauth)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
