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.
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:
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
";
echo "Expires: $expires
";
echo "Refresh Token: $refreshToken
";
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.