tourze / baidu-oauth2-integrate-bundle
Symfony bundle: Baidu OAuth2 integration with DB-backed configuration (Entity-based).
Installs: 30
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
Type:symfony-bundle
pkg:composer/tourze/baidu-oauth2-integrate-bundle
Requires
- doctrine/dbal: ^4.0
- doctrine/doctrine-bundle: ^2.13
- doctrine/orm: ^3.0
- doctrine/persistence: ^4.1
- easycorp/easyadmin-bundle: ^4
- knplabs/knp-menu: ^3.7
- monolog/monolog: ^3.1
- psr/log: ^3|^2|^1
- symfony/cache-contracts: ^3
- symfony/config: ^7.3
- symfony/console: ^7.3
- symfony/dependency-injection: ^7.3
- symfony/doctrine-bridge: ^7.3
- symfony/event-dispatcher-contracts: ^3
- symfony/framework-bundle: ^7.3
- symfony/http-client: ^7.3
- symfony/http-client-contracts: ^3.6
- symfony/http-foundation: ^7.3
- symfony/http-kernel: ^7.3
- symfony/property-access: ^7.3
- symfony/routing: ^7.3
- symfony/security-bundle: ^7.3
- symfony/security-core: ^7.3
- symfony/validator: ^7.3
- symfony/yaml: ^7.3
- tourze/bundle-dependency: 1.*
- tourze/doctrine-indexed-bundle: 1.0.*
- tourze/doctrine-timestamp-bundle: 1.1.*
- tourze/easy-admin-menu-bundle: 1.0.*
- tourze/symfony-dependency-service-loader: 1.0.*
- tourze/symfony-routing-auto-loader-bundle: 1.0.*
Requires (Dev)
README
A Symfony bundle that provides Baidu OAuth2 integration for Symfony applications with database-backed configuration and Entity-based management.
Features
- π Complete OAuth2 Flow: Full implementation of Baidu OAuth2 authorization process
- ποΈ Database Configuration: Entity-based configuration management supporting multiple and dynamic configs
- ποΈ Symfony Integration: Fully compatible with Symfony 7.x ecosystem
- π‘οΈ State Management: Built-in CSRF protection and state token management
- π EasyAdmin Backend: Complete admin interface for management
- π§ Flexible Configuration: Support for custom scopes and redirect URIs
- π§ͺ Complete Testing: Comprehensive unit and integration tests
- π Detailed Logging: Full debugging and error logging
Installation
Install using Composer:
composer require tourze/baidu-oauth2-integrate-bundle
Quick Start
1. Enable Bundle
Add to your config/bundles.php:
return [ // ... Tourze\BaiduOauth2IntegrateBundle\BaiduOauth2IntegrateBundle::class => ['all' => true], ];
2. Database Configuration
The bundle provides three main entities:
BaiduOAuth2Config: OAuth2 application configurationBaiduOAuth2State: State token managementBaiduOAuth2User: User information storage
Create and run database migrations:
php bin/console doctrine:migrations:diff php bin/console doctrine:migrations:migrate
3. Basic Usage
Generate Authorization URL
use Tourze\BaiduOauth2IntegrateBundle\Service\BaiduOAuth2Service; class AuthController extends AbstractController { public function __construct( private BaiduOAuth2Service $oauth2Service ) {} #[Route('/baidu/login', name: 'baidu_login')] public function login(): Response { $authUrl = $this->oauth2Service->generateAuthorizationUrl(); return $this->redirect($authUrl); } }
Handle Callback
#[Route('/baidu/callback', name: 'baidu_callback')] public function callback(Request $request): Response { $code = $request->query->get('code'); $state = $request->query->get('state'); try { $user = $this->oauth2Service->handleCallback($code, $state); // Handle user login logic return $this->redirectToRoute('dashboard'); } catch (BaiduOAuth2Exception $e) { // Handle OAuth2 errors return $this->redirectToRoute('login_failed'); } }
Configuration
Basic Configuration
Add to config/packages/baidu_oauth2.yaml:
baidu_oauth2_integrate: # Redirect URI (optional, defaults to route 'baidu_oauth2_callback') redirect_uri: 'https://your-domain.com/baidu/callback' # Default scope (optional) default_scope: 'basic' # State token TTL in seconds state_ttl: 600 # Enable debug logging debug: false
EasyAdmin Backend Management
The bundle automatically integrates with EasyAdmin, providing:
- OAuth2 configuration management
- User information management
- State token management
API Documentation
Main Services
BaiduOAuth2Service
The main OAuth2 flow service.
class BaiduOAuth2Service { // Generate authorization URL public function generateAuthorizationUrl(?string $sessionId = null): string // Handle authorization callback public function handleCallback(string $code, string $state): BaiduOAuth2User // Refresh access token public function refreshToken(string $refreshToken): array }
BaiduApiClient
Baidu API client for calling Baidu Open Platform APIs.
class BaiduApiClient { // Get user information public function getUserInfo(string $accessToken): array // Refresh token public function refreshToken(string $refreshToken, string $clientId, string $clientSecret): array }
Routes
The bundle automatically registers the following routes:
baidu_oauth2_login: Baidu login entry pointbaidu_oauth2_callback: Baidu authorization callback
Entity Documentation
BaiduOAuth2Config
OAuth2 application configuration entity:
class BaiduOAuth2Config { private ?int $id; // Configuration ID private string $clientId; // Baidu API Key private string $clientSecret; // Baidu Secret Key private ?string $scope; // Authorization scope private bool $valid; // Is enabled private \DateTime $createdAt; // Created time private \DateTime $updatedAt; // Updated time }
BaiduOAuth2User
User information entity:
class BaiduOAuth2User { private ?int $id; // User ID private string $openid; // Baidu OpenID private ?string $unionid; // Baidu UnionID private ?string $accessToken; // Access token private ?string $refreshToken; // Refresh token private ?\DateTime $tokenExpiresAt; // Token expiration time private ?array $userInfo; // User information private \DateTime $createdAt; // Created time private \DateTime $updatedAt; // Updated time }
BaiduOAuth2State
State token entity:
class BaiduOAuth2State { private ?int $id; // State ID private string $state; // State token private ?string $sessionId; // Session ID private bool $used; // Is used private \DateTime $expiresAt; // Expiration time private BaiduOAuth2Config $config; // Associated configuration private \DateTime $createdAt; // Created time private \DateTime $updatedAt; // Updated time }
Testing
Run the test suite:
# Run all tests php bin/console phpunit # Run specific test php bin/console phpunit tests/Service/BaiduOAuth2ServiceTest.php
Events
The bundle provides the following Symfony events:
BaiduOAuth2TokenReceivedEvent: Token received successfullyBaiduOAuth2UserCreatedEvent: User information createdBaiduOAuth2TokenRefreshedEvent: Token refreshed successfully
Error Handling
The bundle provides dedicated exception classes:
use Tourze\BaiduOauth2IntegrateBundle\Exception\BaiduOAuth2Exception; // Catch OAuth2 related errors try { $user = $oauth2Service->handleCallback($code, $state); } catch (BaiduOAuth2Exception $e) { // Handle error $this->logger->error('Baidu OAuth2 error: ' . $e->getMessage()); }
Logging Configuration
Configure logging:
# config/packages/monolog.yaml monolog: handlers: baidu_oauth2: type: stream path: '%kernel.logs_dir%/baidu_oauth2.log' level: info channels: ['baidu_oauth2']
Security Considerations
- Redirect URI Security: Ensure redirect URIs are properly configured in Baidu Open Platform
- State Token Validation: Bundle automatically handles state token validation to prevent CSRF attacks
- Token Security: Access and refresh tokens are encrypted and stored in database
- HTTPS: Production environment must use HTTPS
- Key Management: Properly secure API Key and Secret Key
License
This project is licensed under the MIT License.
Contributing
Issues and Pull Requests are welcome. Please ensure:
- Follow PSR-12 coding standards
- Add appropriate tests
- Update relevant documentation
Changelog
See CHANGELOG.md for version updates.
Support
- π§ Email: support@tourze.com
- π Issue Reporting: GitHub Issues
- π Documentation: Project Wiki