## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require chaima409/oauth-server-bundle
Add to config/bundles.php:
Chaima409\OAuthServerBundle\Chaima409OAuthServerBundle::class => ['all' => true],
Configuration:
Enable the bundle in config/packages/chaima409_oauth_server.yaml (create if missing):
chaima409_oauth_server:
db_driver: orm # or 'pdo' for PDO-based storage
token_param_name: # Customize token param if needed
access_token: access_token
refresh_token: refresh_token
access_token_lifetime: 3600 # Default: 1 hour (in seconds)
refresh_token_lifetime: 2592000 # Default: 30 days
First Use Case:
fos_oauth_server:client:create command:
php bin/console fos_oauth_server:client:create --redirect-uri=http://localhost --grant-types=password,refresh_token
/oauth/v2/token with:
{
"grant_type": "password",
"client_id": "your_client_id",
"client_secret": "your_client_secret",
"username": "user@example.com",
"password": "password"
}
Response:
{
"access_token": "abc123...",
"expires_in": 3600,
"refresh_token": "xyz456..."
}
Where to Look First:
src/Entity/ for Client, AccessToken, and RefreshToken entities (auto-generated if using ORM)./oauth/v2/.Resources/doc/index.md for grant types, scopes, and customization.Client Management:
$client = new Client();
$client->setRandomId();
$client->setSecret('secure_secret');
$client->addRedirectUri('https://yourapp.com/callback');
$client->addGrantType('password');
$em->persist($client);
$em->flush();
authorization_code, password, refresh_token, client_credentials. Enable/disable via YAML:
chaima409_oauth_server:
grant_types:
- password
- refresh_token
Token Handling:
access_token_lifetime. Extend lifetime via:
$token = $this->get('chaima409_oauth_server.token_manager')->createAccessToken($client, $user, ['scope1', 'scope2'], 7200); // 2 hours
refresh_token grant to issue new access tokens:
POST /oauth/v2/token
grant_type=refresh_token&refresh_token=xyz456...
Authentication Integration:
UserProvider to validate credentials:
use Chaima409\OAuthServerBundle\Security\User\UserProviderInterface;
class CustomUserProvider implements UserProviderInterface {
public function loadUserByUsername($username) {
// Your logic to fetch user
}
}
Register as a service:
services:
chaima409_oauth_server.user_provider:
class: App\Security\CustomUserProvider
Scopes:
chaima409_oauth_server:
scopes:
read: Grants read access
write: Grants write access
$token = $this->get('chaima409_oauth_server.token_manager')->createAccessToken($client, $user, ['read', 'write']);
API Protection:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
/**
* @Security("is_granted('IS_AUTHENTICATED_FULLY')")
*/
public function secureAction() { ... }
access_control:
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
Custom Grant Types:
GrantTypeInterface:
use Chaima409\OAuthServerBundle\Grant\GrantTypeInterface;
class CustomGrantType implements GrantTypeInterface {
public function getName() { return 'custom'; }
public function authenticate(Request $request) { ... }
}
services:
chaima409_oauth_server.grant_type.custom:
class: App\Grant\CustomGrantType
tags:
- { name: chaima409_oauth_server.grant_type }
Token Storage:
Token entities are properly mapped to the database. ORM is recommended for complex queries.// In your RefreshToken entity
public function __destruct() {
if ($this->getExpiration() < new \DateTime()) {
// Delete or mark as expired
}
}
Security:
parameter_bag./oauth/v2/token in Symfony’s security config:
security:
access_control:
- { path: ^/oauth/v2/token, roles: PUBLIC_ACCESS }
Configuration Quirks:
/oauth/v2/token) are not found, ensure:
bundles.php.prePersist/preUpdate to auto-generate IDs or timestamps:
$client->setRandomId(); // For Client entity
$token->setCreatedAt(new \DateTime()); // For Token entities
Debugging:
TokenManager to validate tokens manually:
$tokenManager = $this->get('chaima409_oauth_server.token_manager');
$token = $tokenManager->findToken('access_token_here');
if (!$token || $token->isExpired()) {
throw new \RuntimeException('Invalid token');
}
chaima409_oauth_server:
debug: true
Extension Points:
TokenResponse class and configuring a custom service:
services:
chaima409_oauth_server.response:
class: App\OAuth\CustomTokenResponse
public: false
oauth.server.token.created):
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Chaima409\OAuthServerBundle\Event\TokenEvent;
class OAuthEventSubscriber implements EventSubscriberInterface {
public static function getSubscribedEvents() {
return [
TokenEvent::TOKEN_CREATED => 'onTokenCreated',
];
}
public function onTokenCreated(TokenEvent $event) {
// Custom logic (e.g., log tokens, send notifications)
}
}
Performance:
$cache = $this->get('cache.app');
$cacheKey = 'oauth_token_' . $tokenId;
if (!$cache->has($cacheKey)) {
$token = $tokenManager->findToken($tokenId);
$cache->set($cacheKey, $token, 60); // Cache for 60 seconds
}
Testing:
How can I help you explore Laravel packages today?