chez14 / oauth2-authentik
Authentik OAuth2 Client
Requires
- league/oauth2-client: ^2.8
Requires (Dev)
- mockery/mockery: ^1.6
- pestphp/pest: ^3.8
This package is auto-updated.
Last update: 2025-05-03 15:18:54 UTC
README
This package provides Authentik OAuth 2.0 support for the PHP League's OAuth 2.0 Client.
Installation
To install, use Composer (via Packagist
[chez14/oauth2-authentik
][packagist:chez14/oauth2-authentik]):
composer require chez14/oauth2-authentik
[packagist:chez14/oauth2-authentik]:
https://packagist.org/packages/chez14/oauth2-authentik
Usage
Usage is similar to the League's OAuth client, using
\CHEZ14\OAuth2\Client\Provider\AuthentikProvider
as the provider.
$provider = new \CHEZ14\OAuth2\Client\Provider\AuthentikProvider([
'clientId' => '{authentik-client-id}',
'clientSecret' => '{authentik-client-secret}',
'redirectUri' => 'https://example.com/callback-url',
'authentikUri' => 'https://authentik.example.com', // Your Authentik instance URL
'pkce' => true, // Optional: Enable PKCE (recommended for security)
]);
if (!isset($_GET['code'])) {
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->getState();
header('Location: ' . $authUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// Optional: Now you have a token you can look up a users profile data
try {
// We got an access token, let's now get the user's details
$user = $provider->getResourceOwner($token);
// Use these details to create a new profile
printf('Hello %s!\n', $user->getId());
// Use this to interact with an API on the users behalf
echo $token->getToken();
} catch (\Exception $e) {
// Failed to get user details
exit('Something went wrong: ' . $e->getMessage());
}
}
Managing Scopes
When creating your Authentik authorization URL, you can specify the state and scopes your application may authorize.
$options = [
'scope' => ['openid', 'email', 'profile']
];
$authorizationUrl = $provider->getAuthorizationUrl($options);
If neither are defined, the provider will utilize the defaults defined in the provider.
PKCE Support
This provider supports PKCE (Proof Key for Code Exchange) which is recommended
for additional security. You can enable it by setting the pkce
option to
true
in the provider configuration:
$provider = new \CHEZ14\OAuth2\Client\Provider\AuthentikProvider([
// ... other options
'pkce' => true,
]);
Testing
composer test
License
The MIT License (MIT). Please see License File for more information.