PHP code example of itk-dev / openid-connect-bundle

1. Go to this page and download the library: Download itk-dev/openid-connect-bundle 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/ */

    

itk-dev / openid-connect-bundle example snippets


use ItkDev\OpenIdConnectBundle\Util\ClientSecretExpiry;
use ItkDev\OpenIdConnectBundle\Util\ClientSecretExpiryChecker;

// Shape will differ per application; this follows a tagged-service aggregator.
readonly class ClientSecretHealthCheck implements HealthCheckInterface
{
    public function __construct(private ClientSecretExpiryChecker $expiryChecker)
    {
    }

    public function getName(): string
    {
        return 'oidc_client_secret';
    }

    public function check(): HealthCheckResult
    {
        $statuses = $this->expiryChecker->getAllStatuses();

        $expired = array_filter($statuses, static fn (ClientSecretExpiry $e): bool => $e->isExpired());
        if ([] !== $expired) {
            return HealthCheckResult::degraded($this->getName(), sprintf(
                'Client secret expired for: %s',
                implode(', ', array_keys($expired)),
            ));
        }

        $expiring = array_filter($statuses, static fn (ClientSecretExpiry $e): bool => $e->isExpiringSoon());
        if ([] !== $expiring) {
            return HealthCheckResult::degraded($this->getName(), sprintf(
                'Client secret expires soon for: %s',
                implode(', ', array_keys($expiring)),
            ));
        }

        return HealthCheckResult::ok($this->getName());
    }
}

  $router->generate('itkdev_openid_connect_login', ['provider => 'user']);



namespace App\Security;

use ItkDev\OpenIdConnect\Exception\ItkOpenIdConnectException;
use ItkDev\OpenIdConnectBundle\Security\OpenIdLoginAuthenticator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;

class SomeAuthenticator extends OpenIdLoginAuthenticator
{

    public function authenticate(Request $request): Passport
    {
        // Get the OIDC claims.
        try {
            $claims = $this->validateClaims($request);
            
            // Authentication success
            
            // TODO: Implement authenticate() method.
            
        } catch (ItkOpenIdConnectException $exception) {
            // Authentication failed. Chain the cause: the bundle reads it back in
            // onAuthenticationFailure() to decide what the user is shown.
            throw new CustomUserMessageAuthenticationException($exception->getMessage(), previous: $exception);
        }
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        // Back to whatever the user was trying to reach, or your default.
        return $this->createTargetPathRedirect($request, $firewallName, '/');
    }

    public function start(Request $request, AuthenticationException $authException = null)
    {
        // TODO: Implement start() method.
    }
}

protected function getSupportedProviderKeys(): array
{
    return ['admin'];
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
    return $this->createTargetPathRedirect($request, $firewallName, $this->router->generate('dashboard'));
}



namespace App\Security;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use ItkDev\OpenIdConnect\Exception\ItkOpenIdConnectException;
use ItkDev\OpenIdConnectBundle\Exception\InvalidProviderException;
use ItkDev\OpenIdConnectBundle\Security\OpenIdConfigurationProviderManager;
use ItkDev\OpenIdConnectBundle\Security\OpenIdLoginAuthenticator;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;

class AzureOIDCAuthenticator extends OpenIdLoginAuthenticator
{
    /**
     * AzureOIDCAuthenticator constructor
     *
     * @param EntityManagerInterface $entityManager
     * @param RequestStack $requestStack
     * @param UrlGeneratorInterface $router
     * @param OpenIdConfigurationProviderManager $providerManager
     */
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly RequestStack $requestStack,
        private readonly UrlGeneratorInterface $router,
        private readonly OpenIdConfigurationProviderManager $providerManager
    ) {
        parent::__construct($providerManager);
    }

    /** @inheritDoc */
    public function authenticate(Request $request): Passport
    {
        try {
            // Validate claims
            $claims = $this->validateClaims($request);

            // Extract properties from claims
            $name = $claims['name'];
            $email = $claims['upn'];

            // Check if user exists already - if not create a user
            $user = $this->entityManager->getRepository(User::class)
                ->findOneBy(['email'=> $email]);
            if (null === $user) {
                // Create the new user and persist it
                $user = new User();
                $this->entityManager->persist($user);
            }
            // Update/set user properties
            $user->setName($name);
            $user->setEmail($email);

            $this->entityManager->flush();

            return new SelfValidatingPassport(new UserBadge($user->getUserIdentifier()));
        } catch (ItkOpenIdConnectException|InvalidProviderException $exception) {
            throw new CustomUserMessageAuthenticationException($exception->getMessage(), previous: $exception);
        }
    }

    /** @inheritDoc */
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        return $this->createTargetPathRedirect(
            $request,
            $firewallName,
            $this->router->generate('homepage_authenticated')
        );
    }

    /** @inheritDoc */
    public function start(Request $request, AuthenticationException $authException = null): Response
    {
        return new RedirectResponse($this->router->generate('itkdev_openid_connect_login', [
            'provider' => 'user',
        ]));
    }
}

use ItkDev\OpenIdConnectBundle\Exception\ProviderErrorException;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

#[AsEventListener(KernelEvents::EXCEPTION, priority: 1)]
public function onLoginRefused(ExceptionEvent $event): void
{
    $exception = $event->getThrowable();

    if (!$exception instanceof ProviderErrorException) {
        return;
    }

    $template = ProviderErrorException::ACCESS_DENIED === $exception->getError()
        ? 'security/login_cancelled.html.twig'
        : 'security/login_failed.html.twig';

    $event->setResponse(new Response(
        $this->twig->render($template, ['error' => $exception->getError()]),
        $exception->getStatusCode(),
    ));
}

// Wrong: the next request through this process sees the previous user's claims.
private array $claims;

public function authenticate(Request $request): Passport
{
    $this->claims = $this->validateClaims($request);
    // ...
}
shell
task lint:php:fix