PHP code example of keenthekeen / oauth-helper

1. Go to this page and download the library: Download keenthekeen/oauth-helper library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

keenthekeen / oauth-helper example snippets


// config/auth.php
'guards' => [
    'api' => ['driver' => 'oauth'],
],

Gate::define('students_basic', fn ($user) => $user instanceof ApiClient && $user->hasScope('students_basic'));

use Keenthekeen\OAuthHelper\Facades\OAuth;

// Token cached per client, scope and resource until shortly before it expires
$token = OAuth::token('orders:read', resource: 'https://orders.example.com');

// Pending request with the token, JSON headers and the configured timeouts
$response = OAuth::http('customers:read')->get('https://crm.example.com/api/customers');

// GraphQL shortcut
$response = OAuth::graphql('https://crm.example.com/graphql', $query, ['first' => 100], scope: 'customers:read');
$users = $response->json('data.users');

use Keenthekeen\OAuthHelper\Sso\OidcSessionRegistry;
use Keenthekeen\OAuthHelper\ThaiName\ThaiName;
use Keenthekeen\OAuthHelper\Token\StrongAuth;

public function callback(Request $request, OidcSessionRegistry $sessions) {
    $providerUser = Socialite::driver('oidc_keycloak')->user();
    $claims = $providerUser->user; // claims of the verified id_token

    $user = User::firstOrCreate(['email' => $providerUser->getEmail()], ['name' => $providerUser->getName()]);
    if ($name = ThaiName::preferredName($user->name, $claims)) {
        $user->update(['name' => $name]);
    }
    Auth::login($user);

    $sessions->remember($request, $user, $claims, $providerUser->accessTokenResponseBody['id_token'] ?? null);
    $request->session()->put('sso-acr-strong', StrongAuth::fromClaims($claims));
    // ...
}

$idToken = app(OidcSessionRegistry::class)->forget($request);
return redirect(app(OidcSessionRegistry::class)->logoutUrl($idToken, url('/')));

// bootstrap/app.php → withRouting(then: fn () => Route::oidcBackchannelLogout())
Route::oidcBackchannelLogout(); // POST auth/sso/backchannel-logout, named sso.backchannel-logout

use Keenthekeen\OAuthHelper\Directory\SearchMode;

$users = OAuth::users()->search('somchai');                    // prefix match on username, email, first/last name
$users = OAuth::users()->search('jaidee', SearchMode::Infix, max: 20);
$user = OAuth::users()->findByUsername('jdoe');
$user = OAuth::users()->findByEmail('[email protected]');
$users = OAuth::users()->findByAttribute('employeeId', 'E12345');
$count = OAuth::users()->count('somchai');

$user->email; $user->attribute('employeeId'); $user->thaiName()?->full();

ThaiName::split('สมศรี ณ อยุธยา');            // first: สมศรี, last: ณ อยุธยา
ThaiName::fromClaims($claims)?->full();       // from the thai_names client scope, null if missing or corrupted
ThaiName::preferredName($user->name, $claims); // name to save on login, or null to keep the stored one
ThaiName::hasEncodingFault($text);             // U+FFFD in a wrongly encoded name from an upstream directory

// config/auth.php
'guards' => ['mcp' => ['driver' => 'oauth-mcp']],

// routes/ai.php
Route::mcpProtectedResource(); // /.well-known/oauth-protected-resource/{path?}, advertised in Laravel MCP's 401s
Mcp::web('/mcp', AppServer::class)->middleware(['auth:mcp', 'throttle:60,1']);

use Keenthekeen\OAuthHelper\Testing\FakeOAuthServer;

beforeEach(fn () => $this->server = FakeOAuthServer::install());

it('serves another service', function () {
    $this->withToken($this->server->apiToken('reporting', ['students_basic']))
        ->postJson('/graphql', ['query' => '{ me { id } }'])
        ->assertOk();
});

it('serves an MCP client', function () {
    $this->withToken($this->server->mcpToken($user->email, strongAuth: true))->postJson('/mcp', [...]);
});

it('searches users', function () {
    $directory = $this->server->fakeUsers([['username' => 'somchai', 'email' => '[email protected]']]);
    // ...
    $directory->assertSearched('somchai');
});

// Outgoing calls: answer client credentials grants
$this->server->fakeTokenEndpoint();