microsoft/kiota-authentication-phpleague
Install the package:
composer require microsoft/kiota-authentication-phpleague
Basic OAuth2 Authentication:
use Microsoft\Kiota\Authentication\PhpLeague\ProviderFactory;
use League\OAuth2\Client\Provider\MicrosoftProvider;
// Configure OAuth2 provider
$provider = new MicrosoftProvider([
'clientId' => 'your-client-id',
'clientSecret' => 'your-client-secret',
'redirectUri' => 'your-redirect-uri',
]);
// Create Kiota auth provider
$authProvider = ProviderFactory::create($provider);
// Use with Kiota client
$kiotaClient = new YourGeneratedClient();
$kiotaClient->setAuthentication($authProvider);
First Use Case - Interactive Login:
$authUrl = $authProvider->getAuthUrl();
// Redirect user to $authUrl
// After user authorizes, handle callback:
$token = $authProvider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
ProviderFactory: Central class for creating authentication providers.PhpLeagueAccessTokenProvider: Core class handling token management.InMemoryAccessTokenCache: Default token cache implementation (extendable).// Basic provider
$provider = ProviderFactory::create(new MicrosoftProvider([
'clientId' => env('CLIENT_ID'),
'clientSecret' => env('CLIENT_SECRET'),
'redirectUri' => env('REDIRECT_URI'),
]));
// With custom client options
$provider = ProviderFactory::create(
new MicrosoftProvider([...]),
['customOption' => true]
);
// Get cache instance
$cache = $provider->getAccessTokenCache();
// Pre-populate cache (e.g., from session)
$cache->set('user:123', $existingToken);
// Clear cache for specific user
$cache->remove('user:123');
// For user delegation (e.g., Graph API)
$provider = ProviderFactory::create(
new MicrosoftProvider([...]),
['scopes' => ['User.Read']]
);
// For app-only permissions
$provider = ProviderFactory::create(
new MicrosoftProvider([...]),
['authStyle' => 'app']
);
use Http\Client\Common\Plugin\HeaderHandlerPlugin;
use Http\Client\Common\Plugin\LoggerPlugin;
$client = new \Http\Client\Common\PluginClient(
new \Http\Adapter\Guzzle7\Client(),
[
new HeaderHandlerPlugin(['User-Agent' => 'MyApp/1.0']),
new LoggerPlugin()
]
);
$provider = ProviderFactory::create(
new MicrosoftProvider([...]),
['httpClient' => $client]
);
// Service Provider
public function register()
{
$this->app->singleton('kiota.auth', function ($app) {
$provider = new MicrosoftProvider([
'clientId' => config('services.microsoft.client_id'),
'clientSecret' => config('services.microsoft.client_secret'),
'redirectUri' => config('services.microsoft.redirect_uri'),
]);
return ProviderFactory::create($provider);
});
}
// Controller
public function handleCallback()
{
$authProvider = app('kiota.auth');
$token = $authProvider->getAccessToken('authorization_code', [
'code' => request('code')
]);
// Store token in session/DB
session(['access_token' => $token->getToken()]);
}
Environment Configuration:
// config/services.php
'microsoft' => [
'client_id' => env('MICROSOFT_CLIENT_ID'),
'client_secret' => env('MICROSOFT_CLIENT_SECRET'),
'redirect_uri' => env('MICROSOFT_REDIRECT_URI'),
'scopes' => ['User.Read', 'Mail.Read'],
]
Token Refresh Handling:
try {
$token = $authProvider->getAccessToken();
} catch (\League\OAuth2\Client\Provider\Exception\TokenExpiredException $e) {
// Refresh token logic
$refreshToken = session('refresh_token');
$token = $authProvider->getAccessToken('refresh_token', [
'refresh_token' => $refreshToken
]);
}
Middleware for Protected Routes:
public function handle($request, Closure $next)
{
$authProvider = app('kiota.auth');
$token = $authProvider->getAccessToken();
$request->headers->set('Authorization', 'Bearer ' . $token->getToken());
return $next($request);
}
PHP Version Requirements:
Token Cache Key Collisions:
$cache = new InMemoryAccessTokenCache();
$cache->set('user:123:app', $token); // Add user/app identifier
Redirect URI Mismatch:
'redirectUri' => 'https://yourdomain.com/auth/callback'
Scopes Not Requested:
$provider = ProviderFactory::create($oauthProvider, [
'scopes' => ['User.Read', 'Mail.ReadWrite']
]);
Token Expiration Handling:
Enable HTTP Logging:
$client = new \Http\Client\Common\PluginClient(
new \Http\Adapter\Guzzle7\Client(),
[new \Http\Client\Common\Plugin\LoggerPlugin(true)]
);
Check Token Response:
$token = $authProvider->getAccessToken('authorization_code', [...]);
\Log::info('Token response:', $token->toArray());
Validate OAuth2 Provider:
try {
$provider = new MicrosoftProvider([...]);
$provider->getBaseAuthorizationUrl(); // Throws if invalid config
} catch (\Exception $e) {
\Log::error('OAuth2 config error:', $e->getMessage());
}
Custom Token Cache:
use Microsoft\Kiota\Authentication\PhpLeague\TokenCache;
class DatabaseTokenCache implements TokenCache {
public function get($key) { /* ... */ }
public function set($key, $token) { /* ... */ }
public function remove($key) { /* ... */ }
}
// Usage
$provider = ProviderFactory::create($oauthProvider, [
'tokenCache' => new DatabaseTokenCache()
]);
Custom Auth Flow:
$authProvider->setAuthCodeContext(new AuthCodeContext([
'code' => $code,
'redirectUri' => $redirectUri,
'state' => $state,
'scopes' => $scopes
]));
Override Default URLs:
$provider = ProviderFactory::create($oauthProvider, [
'tokenUrl' => 'https://login.microsoftonline.com/your-tenant/oauth2/v2.0/token',
'userInfoUrl' => 'https://graph.microsoft.com/oidc/userinfo'
]);
Localhost URLs:
http:// scheme for localhost (not just https://).Client Credentials Flow:
authStyle is set to 'app':
$provider = ProviderFactory::create($oauthProvider, [
'authStyle' => 'app'
]);
Token Validation:
$provider = ProviderFactory::create($oauthProvider, [
'validateToken' => false
]);
How can I help you explore Laravel packages today?