## Getting Started
### Minimal Setup
1. **Installation**
```bash
composer require akeneo/oauth-server-bundle
Add to config/bundles.php:
return [
// ...
Akeneo\OAuthServerBundle\AkeneoOAuthServerBundle::class => ['all' => true],
];
Configure OAuth2 Server
Update config/packages/oauth_server.yaml (auto-generated after installation):
oauth_server:
db_driver: orm # or 'mongodb', 'propel', etc.
client_class: # Custom client entity (optional)
App\Entity\OAuthClient
access_token_class: # Custom access token entity (optional)
App\Entity\OAuthAccessToken
refresh_token_class: # Custom refresh token entity (optional)
App\Entity\OAuthRefreshToken
auth_code_class: # Custom auth code entity (optional)
App\Entity\OAuthAuthCode
service:
user_provider: # Link to your user provider (e.g., FOSUserBundle)
id: fos_user.user_provider.username_email
First Use Case: Protect an API Endpoint
Annotate a controller method with @OAuth:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
class ApiController extends AbstractController
{
/**
* @Security("is_granted('IS_AUTHENTICATED_FULLY')")
*/
public function secureEndpoint()
{
return $this->json(['data' => 'protected']);
}
}
Generate Clients
Use the fos:oauth-server:create-client command:
php bin/console fos:oauth-server:create-client
(Follow prompts to set random_id, secret, redirect_uri, etc.)
Token Management
fos_oauth_server.token route with POST:
curl -X POST -d 'grant_type=password&username=user&password=pass' http://your-app.com/oauth/v2/token
grant_type with refresh_token and include the refresh token.fos_oauth_server.revoke_token route:
curl -X POST -d 'token=ACCESS_TOKEN' http://your-app.com/oauth/v2/revoke_token
Custom User Providers Extend the default provider to integrate with your user system:
// src/Service/CustomUserProvider.php
use Symfony\Component\Security\Core\User\UserProviderInterface;
class CustomUserProvider implements UserProviderInterface
{
public function loadUserByUsername($username)
{
// Fetch user from your DB/API
return new User(); // Your user entity
}
// ... other required methods
}
Register in config/services.yaml:
services:
App\Service\CustomUserProvider:
tags: ['oauth.user_provider']
Scopes and Roles
Define scopes in the client configuration (e.g., read, write):
# config/packages/oauth_server.yaml
oauth_server:
service:
client_class: App\Entity\OAuthClient
In your OAuthClient entity:
// src/Entity/OAuthClient.php
public function getAllowedScopes()
{
return ['read', 'write']; // Scopes for this client
}
Enforce scopes in controllers:
/**
* @Security("is_granted('ROLE_OAUTH_SCOPE_read')")
*/
public function readData()
{
// ...
}
Integration with FOSUserBundle
If using FOSUserBundle, configure the user provider in oauth_server.yaml:
oauth_server:
service:
user_provider: fos_user.user_provider.username_email
Ensure your User entity implements OAuthAwareInterface:
use Akeneo\OAuthServerBundle\Model\OAuthAwareInterface;
class User implements OAuthAwareInterface
{
// ...
}
Customizing Token Entities
Extend default entities (e.g., OAuthAccessToken) to add custom fields:
// src/Entity/OAuthAccessToken.php
use Akeneo\OAuthServerBundle\Entity\OAuthAccessToken as BaseToken;
class OAuthAccessToken extends BaseToken
{
/**
* @ORM\Column(type="string", nullable=true)
*/
private $customField;
// Getters/setters
}
Update oauth_server.yaml to reference your custom class.
Symfony Security Integration
Use the oauth_token firewall in config/packages/security.yaml:
security:
firewalls:
api:
pattern: ^/api
oauth_token:
check_path: /oauth/v2/token
services:
- App\Service\CustomUserProvider
Testing Tokens
Use the fos:oauth-server:create-token command for testing:
php bin/console fos:oauth-server:create-token --client-id=CLIENT_ID --username=USERNAME
Rate Limiting
Combine with Symfony’s rate_limiter to protect token endpoints:
# config/packages/security.yaml
firewalls:
oauth_token:
rate_limiter: oauth_token_limiter
Logging
Enable OAuth logging in config/packages/monolog.yaml:
handlers:
oauth:
type: stream
path: "%kernel.logs_dir%/oauth.log"
level: debug
channels: ["oauth"]
Database Schema Mismatches
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate
CORS Issues
/oauth/v2/token endpoint may block requests from certain origins. Configure CORS in your frontend or backend:
# config/packages/nelmio_cors.yaml
nelmio_cors:
defaults:
allow_origin: ["*"]
allow_methods: ["POST"]
allow_headers: ["Authorization", "Content-Type"]
expose_headers: ["Authorization"]
Token Expiry Quirks
config/packages/oauth_server.yaml:
oauth_server:
service:
access_token_lifetime: 7200 # 2 hours
refresh_token_lifetime: 1209600 # 2 weeks
refresh_token_lifetime to allow long-lived sessions with refreshable tokens.Client Secret Management
# .env
OAUTH_CLIENT_SECRET=your_secret_here
# config/packages/oauth_server.yaml
oauth_server:
service:
client_class: App\Entity\OAuthClient
client_secret: "%env(OAUTH_CLIENT_SECRET)%"
User Provider Conflicts
oauth_server:
service:
user_provider: your_custom_provider_id
PKCE (Proof Key for Code Exchange)
grant_type=authorization_code):
oauth_server:
service:
pkce_support: true
code_verifier and code_challenge).Enable Debug Mode
Set APP_DEBUG=1 in .env to see detailed OAuth errors in logs.
Check Logs
Monitor var/log/oauth.log for token generation/revocation issues.
Validate Token Manually
Use the fos:oauth-server:validate-token command:
php bin/console fos:oauth-server:validate-token ACCESS_TOKEN
Common Errors
invalid_grant: Wrong grant_type, username/password, or expired refresh token.
unsupported_grant_type: Missing or incorrect grant_type in the request.
How can I help you explore Laravel packages today?