PHP code example of gpht / oidc

1. Go to this page and download the library: Download gpht/oidc 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/ */

    

gpht / oidc example snippets




declare(strict_types=1);

use Gpht\Oidc\Client\OidcClientToken;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\HttpClient\HttpClient;

// Create HTTP client
$httpClient = HttpClient::create();

// Create PSR-6 cache (n',
    cognitoClientId: 'your-client-id',
    cognitoClientSecret: 'your-client-secret'
);

// Get access token with default scopes (m2m/read, m2m/write)
// Token will be cached automatically with expiration handling
$token = $oidcClientToken->clientCredentialToken();

// Get access token with custom scopes
$token = $oidcClientToken->clientCredentialToken(['custom/read', 'custom/write']);



declare(strict_types=1);

use Gpht\Oidc\Client\OidcClientToken;
use Gpht\Oidc\Symfony\OidcUserProvider;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Contracts\HttpClient\HttpClientInterface;

return static function (ContainerConfigurator $containerConfigurator): void {
    $s = $containerConfigurator->services();
    $s
        ->defaults()
        ->autowire()
        ->autoconfigure();

    // Configure OIDC Client Token service
    $s
        ->set(OidcClientToken::class)
        ->arg('$cache', service('cache.app'))  // Use Symfony's cache service
        ->arg('$tokenEndpoint', '%env(COGNITO_TOKEN_ENDPOINT)%')
        ->arg('$cognitoClientId', '%env(COGNITO_CLIENT_ID)%')
        ->arg('$cognitoClientSecret', '%env(COGNITO_CLIENT_SECRET)%');

    // Configure OIDC User Provider service
    $s
        ->set(OidcUserProvider::class);
};



declare(strict_types=1);

use Gpht\Oidc\Symfony\OidcUserProvider;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Config\SecurityConfig;

return static function (ContainerConfigurator $containerConfigurator, SecurityConfig $securityConfig): void {
    $parameters = $containerConfigurator->parameters();
    $parameters->set('env(OIDC_BASE_URI)', 'https://your-cognito-domain.auth.region.amazoncognito.com');

    // Register OIDC user provider
    $securityConfig
        ->provider('oidc')
        ->id(OidcUserProvider::class);

    // Configure OIDC firewall
    $securityConfig
        ->firewall('api')
        ->provider('oidc')
        ->pattern('^/api/')
        ->stateless(true)
        ->accessToken()
            ->tokenHandler()
                ->oidc()
                    ->claim('sub')
                    ->algorithms(['ES256', 'RS256'])
                    ->audience('')
                    ->issuers(['%env(OIDC_BASE_URI)%'])
                    ->discovery()
                        ->baseUri('%env(OIDC_BASE_URI)%')
                        ->cache(['id' => 'cache.app']);
};



declare(strict_types=1);

namespace App\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/api')]
final readonly class ApiController
{
    public function __construct(
        private TokenStorageInterface $tokenStorage,
    ) {}

    #[Route('/profile', methods: ['GET'])]
    #[IsGranted('IS_AUTHENTICATED_FULLY')]
    public function profile(): JsonResponse
    {
        $token = $this->tokenStorage->getToken();
        $user = $token?->getUser();

        if (null === $user) {
            return new JsonResponse(['error' => 'User not authenticated'], 401);
        }

        return new JsonResponse([
            'user_id' => $user->getUserIdentifier(),
            'roles' => $user->getRoles(),
            'email' => $user->getEmail(),
            'name' => $user->getName(),
        ]);
    }
}



declare(strict_types=1);

use Gpht\Oidc\Client\OidcClientToken;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class ApiTest extends WebTestCase
{
    public function testAuthenticatedEndpoint(): void
    {
        $client = static::createClient();
        
        /** @var OidcClientToken $oidcClientToken */
        $oidcClientToken = self::getContainer()->get(OidcClientToken::class);
        $token = $oidcClientToken->clientCredentialToken();

        $client->jsonRequest('GET', '/api/profile', [], [
            'HTTP_AUTHORIZATION' => 'Bearer ' . $token,
        ]);

        $this->assertResponseIsSuccessful();
    }
}