auth0/auth0-php
Auth0 PHP SDK for integrating Auth0 Authentication and Management APIs. Build login/logout flows, validate tokens, and manage users, roles, and applications. Works with any PHP app, with tailored SDKs available for Laravel, Symfony, and WordPress.
## Getting Started
### Minimal Laravel Integration
1. **Install the package** via Composer:
```bash
composer require auth0/auth0-php
php artisan vendor:publish --provider="Auth0\SDK\Auth0ServiceProvider"
.env:
AUTH0_DOMAIN=your-auth0-domain.auth0.com
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret
AUTH0_COOKIE_SECRET=openssl rand -hex 32
AUTH0_CALLBACK_URL=http://your-app.test/auth0/callback
AUTH0_LOGOUT_URL=http://your-app.test
routes/web.php:
use Auth0\SDK\Auth0;
use Auth0\SDK\Configuration\SdkConfiguration;
Route::get('/login', function () {
$config = new SdkConfiguration(
domain: env('AUTH0_DOMAIN'),
clientId: env('AUTH0_CLIENT_ID'),
clientSecret: env('AUTH0_CLIENT_SECRET'),
cookieSecret: env('AUTH0_COOKIE_SECRET')
);
$auth0 = new Auth0($config);
return redirect($auth0->login());
});
// Middleware (e.g., `Auth0Middleware`)
public function handle(Request $request, Closure $next) {
$auth0 = app(Auth0::class);
$credentials = $auth0->getCredentials();
if (!$credentials || $credentials->accessTokenExpired) {
return redirect($auth0->login());
}
return $next($request);
}
Route::get('/auth0/callback', function () {
$auth0 = app(Auth0::class);
if ($auth0->getExchangeParameters()) {
$auth0->exchange();
return redirect('/dashboard');
}
return redirect('/login');
});
$user = $auth0->getCredentials()?->user;
// Use $user->email, $user->sub, etc.
use Auth0\SDK\Management\Auth0ManagementClient;
$managementClient = new Auth0ManagementClient(
domain: env('AUTH0_DOMAIN'),
clientId: env('AUTH0_CLIENT_ID'),
clientSecret: env('AUTH0_CLIENT_SECRET'),
scope: ['read:users', 'update:users']
);
$users = $managementClient->users->listUsers();
foreach ($users as $user) {
// Process user
}
$newUser = $managementClient->users->createUser([
'connection' => 'Username-Password-Authentication',
'email' => 'user@example.com',
'password' => 'securepassword',
'given_name' => 'John',
'family_name' => 'Doe'
]);
use Auth0\SDK\Auth0;
$auth0 = new Auth0(
domain: env('AUTH0_DOMAIN'),
clientId: env('AUTH0_CLIENT_ID'),
clientSecret: env('AUTH0_CLIENT_SECRET')
);
$isValid = $auth0->validateToken($request->bearerToken);
if (!$isValid) {
abort(401, 'Invalid token');
}
$auth0 = app(Auth0::class);
$auth0->getCredentials()->addCustomClaim('custom_role', 'admin');
Cookie Secret Mismanagement:
cookieSecret (e.g., generated via openssl rand -hex 32) can lead to session hijacking..env).Callback URL Mismatch:
AUTH0_CALLBACK_URL in .env matches the exact URL in Auth0 Dashboard (including http/https and trailing slashes).Token Expiry Handling:
401 errors in APIs.$credentials = $auth0->getCredentials();
if ($credentials && $credentials->accessTokenExpired) {
$auth0->refreshToken();
}
Management API Scopes:
read:users) cause 403 errors.$managementClient = new Auth0ManagementClient(
// ...
scope: ['read:users', 'update:users']
);
Enable Verbose Logging:
$config = new SdkConfiguration(
// ...
debug: true
);
storage/logs/laravel.log.Token Debugging:
composer require firebase/php-jwt
use Firebase\JWT\JWT;
$decoded = JWT::decode($token, new \Firebase\JWT\Key('...', 'HS256'));
Management API Errors:
error and error_description fields in responses:
try {
$user = $managementClient->users->getUser('user_id');
} catch (\Auth0\SDK\Exception\SdkException $e) {
dd($e->getResponse()->getBody());
}
Custom HTTP Client:
$httpClient = new \GuzzleHttp\Client([
'timeout' => 10,
'headers' => ['User-Agent' => 'MyApp/1.0']
]);
$config = new SdkConfiguration(
// ...
httpClient: $httpClient
);
Middleware for Token Refresh:
public function handle($request, Closure $next) {
$auth0 = app(Auth0::class);
if ($auth0->getCredentials()?->accessTokenExpired) {
$auth0->refreshToken();
}
return $next($request);
}
V9 Migration:
php artisan vendor:publish --tag=auth0-migrations if the package provides migration helpers.Custom User Attributes:
User model to include Auth0-specific fields:
class Auth0User extends User {
public function getAuth0Id(): string {
return $this->auth0_id ?? '';
}
}
Cache Management API Responses:
$users = Cache::remember('auth0_users', now()->addHours(1), function () {
return $managementClient->users->listUsers();
});
Lazy-Load User Data:
select() for specific fields:
$user = $managementClient->users->getUser('user_id', ['fields' => ['email', 'name']]);
Batch Operations:
deleteUsers) for large-scale operations to reduce API calls.Avoid Hardcoding Secrets:
.env for sensitive data (e.g., AUTH0_CLIENT_SECRET).Secure Cookie Settings:
$config = new SdkConfiguration(
// ...
cookieSettings: [
'secure' => true, // HTTPS only
'httpOnly' => true, // Prevent JS access
'sameSite' => 'Lax', // CSRF protection
]
);
Rate Limiting:
use Illuminate\Cache\RateLimiting
How can I help you explore Laravel packages today?