Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Kiota Authentication Phpleague Laravel Package

microsoft/kiota-authentication-phpleague

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require microsoft/kiota-authentication-phpleague
    
  2. 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);
    
  3. 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']
    ]);
    

Where to Look First

  • ProviderFactory: Central class for creating authentication providers.
  • PhpLeagueAccessTokenProvider: Core class handling token management.
  • InMemoryAccessTokenCache: Default token cache implementation (extendable).

Implementation Patterns

Common Workflows

1. Authentication Provider Creation

// 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]
);

2. Token Caching

// 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');

3. Delegated Permissions

// 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']
);

4. Custom HTTP Client

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]
);

5. Integration with Laravel

// 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()]);
}

Best Practices

  1. 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'],
    ]
    
  2. 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
        ]);
    }
    
  3. 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);
    }
    

Gotchas and Tips

Common Pitfalls

  1. PHP Version Requirements:

    • Minimum PHP 8.2 (since v2.0.0). Ensure your environment meets this requirement.
    • Fix: Update your PHP version or use an older package version (pre-2.0.0).
  2. Token Cache Key Collisions:

    • Default cache keys may collide if not properly namespaced.
    • Fix: Customize cache keys:
      $cache = new InMemoryAccessTokenCache();
      $cache->set('user:123:app', $token); // Add user/app identifier
      
  3. Redirect URI Mismatch:

    • OAuth2 requires exact redirect URI matches.
    • Fix: Configure the exact URI in both your app and Azure AD:
      'redirectUri' => 'https://yourdomain.com/auth/callback'
      
  4. Scopes Not Requested:

    • Tokens are only valid for requested scopes.
    • Fix: Explicitly define scopes:
      $provider = ProviderFactory::create($oauthProvider, [
          'scopes' => ['User.Read', 'Mail.ReadWrite']
      ]);
      
  5. Token Expiration Handling:

    • The library doesn't auto-refresh tokens. Implement your own logic or use middleware.

Debugging Tips

  1. Enable HTTP Logging:

    $client = new \Http\Client\Common\PluginClient(
        new \Http\Adapter\Guzzle7\Client(),
        [new \Http\Client\Common\Plugin\LoggerPlugin(true)]
    );
    
  2. Check Token Response:

    $token = $authProvider->getAccessToken('authorization_code', [...]);
    \Log::info('Token response:', $token->toArray());
    
  3. Validate OAuth2 Provider:

    try {
        $provider = new MicrosoftProvider([...]);
        $provider->getBaseAuthorizationUrl(); // Throws if invalid config
    } catch (\Exception $e) {
        \Log::error('OAuth2 config error:', $e->getMessage());
    }
    

Extension Points

  1. 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()
    ]);
    
  2. Custom Auth Flow:

    $authProvider->setAuthCodeContext(new AuthCodeContext([
        'code' => $code,
        'redirectUri' => $redirectUri,
        'state' => $state,
        'scopes' => $scopes
    ]));
    
  3. 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'
    ]);
    

Configuration Quirks

  1. Localhost URLs:

    • The package allows http:// scheme for localhost (not just https://).
    • Note: Azure AD may still enforce HTTPS for production.
  2. Client Credentials Flow:

    • For app-only permissions, ensure authStyle is set to 'app':
      $provider = ProviderFactory::create($oauthProvider, [
          'authStyle' => 'app'
      ]);
      
  3. Token Validation:

    • The library validates tokens by default. Disable with:
      $provider = ProviderFactory::create($oauthProvider, [
          'validateToken' => false
      ]);
      

Performance Considerations

  1. Cache Invalidation:
    • Implement a TTL (Time-To-Live) for cached tokens to avoid stale tokens:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views