How to create a OAuth and OpenID Connect (OIDC) Authentication in PHP

PHP module that utilizes the league/oauth2-client library to handle OAuth and OpenID Connect (OIDC) authentication.

First, install the required dependency by running composer require league/oauth2-client in your project directory.

				
					<?php
require_once 'vendor/autoload.php';

use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Provider\GenericProvider;

class AuthProvider
{
    private $provider;
    private $clientId;
    private $clientSecret;
    private $redirectUri;
    private $scopes;

    public function __construct()
    {
        $this->clientId = 'your-client-id'; // Client ID registered with the identity provider
        $this->clientSecret = 'your-client-secret'; // Client secret registered with the identity provider
        $this->redirectUri = 'http://localhost:8000/callback'; // Callback URL after authentication
        $this->scopes = ['openid', 'profile', 'email']; // Requested scopes

        $this->provider = new GenericProvider([
            'clientId' => $this->clientId,
            'clientSecret' => $this->clientSecret,
            'redirectUri' => $this->redirectUri,
            'urlAuthorize' => 'https://your-authorization-url.com', // Authorization endpoint URL
            'urlAccessToken' => 'https://your-token-url.com', // Token endpoint URL
            'urlResourceOwnerDetails' => 'https://your-user-info-url.com', // User info endpoint URL
            'scopes' => $this->scopes
        ]);
    }

    public function getAuthorizationUrl(): string
    {
        $authorizationUrl = $this->provider->getAuthorizationUrl(['scope' => $this->scopes]);
        return $authorizationUrl;
    }

    public function authenticate(string $code): array
    {
        $accessToken = $this->provider->getAccessToken('authorization_code', [
            'code' => $code
        ]);

        $resourceOwner = $this->provider->getResourceOwner($accessToken);

        return [
            'access_token' => $accessToken->getToken(),
            'expires' => $accessToken->getExpires(),
            'refresh_token' => $accessToken->getRefreshToken(),
            'resource_owner' => $resourceOwner->toArray()
        ];
    }
}
				
			

To use this module, you’ll need to create an instance of the AuthProvider class and call its methods to initiate the authentication flow and handle the callback.

Here’s an example of how you can use it with a simple PHP script:

				
					<?php
require_once 'AuthProvider.php';

$authProvider = new AuthProvider();

// Initiate authentication by redirecting the user to the authorization URL
if (!isset($_GET['code'])) {
    $authorizationUrl = $authProvider->getAuthorizationUrl();
    header("Location: $authorizationUrl");
    exit;
}

// Handle the callback and authenticate the user
$code = $_GET['code'];
$authData = $authProvider->authenticate($code);

// Access the authentication data
$accessToken = $authData['access_token'];
$expires = $authData['expires'];
$refreshToken = $authData['refresh_token'];
$resourceOwner = $authData['resource_owner'];

// Use the authentication data as needed
echo "Access Token: $accessToken<br>";
echo "Expires: $expires<br>";
echo "Refresh Token: $refreshToken<br>";
echo "Resource Owner: ";
print_r($resourceOwner);
				
			

Make sure to replace 'your-client-id', 'your-client-secret', 'https://your-authorization-url.com', 'https://your-token-url.com', and 'https://your-user-info-url.com' with the appropriate values for your specific identity provider and client.

Please note that this is a basic example, and in a real-world application, you would typically handle error handling, session management, and additional logic based on your specific requirements. Additionally, you may need to configure additional options and implement additional logic depending on your use case.