Install the package:
composer require auth0/symfony
Configure Auth0:
Token Endpoint Authentication Method to POST.Allowed Callback URLs (e.g., http://localhost:8000/callback) and Allowed Logout URLs (e.g., http://localhost:8000/login).Configure Symfony:
auth0.yaml to config/packages/ with environment variables for domain, client_id, client_secret, and routes..env.local with Auth0 credentials and route paths (e.g., AUTH0_ROUTE_CALLBACK=callback).config/bundle.php:
Auth0\Symfony\Auth0Bundle::class => ['all' => true],
config/routes.yaml:
login:
path: /login
controller: Auth0\Symfony\Controllers\AuthenticationController::login
callback:
path: /callback
controller: Auth0\Symfony\Controllers\AuthenticationController::callback
Test Authentication:
/login to trigger Auth0 login./private (configured in .env.local).public function private(): Response {
return new Response(print_r($this->getUser(), true));
}
Session-Based Authentication (Web Apps):
auth0.authenticator in security.yaml for stateful routes (e.g., /private).security.yaml:
firewalls:
auth0:
pattern: ^/private
provider: auth0_provider
custom_authenticators: [auth0.authenticator]
AUTH0_ROUTE_SUCCESS (e.g., /private).AUTH0_ROUTE_FAILURE (e.g., /public).Token-Based Authentication (APIs):
auth0.authorizer for stateless APIs (e.g., /api).security.yaml:
firewalls:
api:
pattern: ^/api
stateless: true
custom_authenticators: [auth0.authorizer]
ROLE_USING_TOKEN: Automatically added to requests with valid tokens.ROLE_READ_MESSAGES) via token scopes.User Data Access:
$user = $this->getUser(); // Auth0User object
$email = $user->getEmail();
$name = $user->getName();
$jwtPayload = $user->getJwtPayload();
Management API:
Auth0\SDK\Auth0 service for API calls:
$auth0 = $container->get('auth0.sdk');
$users = $auth0->users()->listUsers();
management_token_cache in auth0.yaml.Backchannel Logout:
backchannel:
path: /backchannel
controller: Auth0\Symfony\Controllers\BackchannelController::handle
Custom User Provider:
Auth0\Symfony\Security\UserProvider to map Auth0 users to your entities:
class CustomUserProvider extends Auth0UserProvider {
public function loadUserByUsername($username) {
// Custom logic (e.g., fetch from DB)
}
}
security.yaml:
providers:
custom_provider:
id: App\Security\CustomUserProvider
Role Mapping:
Auth0UserProvider:
public function getRoles() {
return ['ROLE_ADMIN']; // Based on Auth0 user metadata
}
Caching:
auth0:
sdk:
token_cache: cache.auth0_token_cache
management_token_cache: cache.auth0_management_token_cache
cache.yaml:
pools:
auth0_token_cache: { adapter: cache.adapter.redis }
Error Handling:
Auth0\SDK\Exception\Auth0Exception for API errors:
try {
$auth0->users()->delete($userId);
} catch (Auth0Exception $e) {
// Log or handle error
}
Testing:
Auth0\SDK\Auth0 in tests:
$auth0 = $this->createMock(Auth0::class);
$auth0->method('getUserInfo')->willReturn(['sub' => 'user123']);
$container->set('auth0.sdk', $auth0);
Environment Variables:
.env.local to .gitignore or committing secrets.env() in auth0.yaml and validate presence:
domain: "%env(AUTH0_DOMAIN)%"
Add validation in config/services.yaml:
parameters:
env(AUTH0_DOMAIN): 'required'
Route Mismatches:
Allowed Callback URLs and Allowed Logout URLs in Auth0 Dashboard.debug:router to verify route paths.Token Expiry:
try {
$auth0->users()->listUsers();
} catch (TokenExpiredException $e) {
$auth0->refreshToken();
retry();
}
CORS for APIs:
Backchannel Logout:
/backchannel route causes logout failures.Enable SDK Logging:
config/packages/monolog.yaml:
handlers:
auth0:
type: stream
path: "%kernel.logs_dir%/auth0.log"
level: debug
channels: ["auth0"]
$auth0->getLogger()->debug('Event', ['data' => $event]);
Validate JWTs Manually:
curl https://{domain}/.well-known/jwks.json
Common Errors:
InvalidClient: Incorrect client_id/client_secret in Auth0 Dashboard.InvalidRedirectURI: Callback URL not whitelisted in Auth0.TokenExpired: Token cache not refreshed (enable token_cache).Custom Authenticator:
Auth0Authenticator to add pre/post-login logic:
class CustomAuthenticator extends Auth0Authenticator {
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName) {
// Log or update user data
return parent::onAuthenticationSuccess($request, $token, $firewallName);
}
}
security.yaml:
custom_authenticators: [App\Security\CustomAuthenticator]
Dynamic Scopes:
getScopes() in Auth0Authenticator to fetch scopes dynamically:
public function getScopes() {
return ['openid', 'profile', 'custom:' . $this->getUserId()];
}
Custom User Claims:
How can I help you explore Laravel packages today?