auth0-laravel
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 Laravel Web App Integration
Auth0 Laravel Web应用集成
Add login, logout, and user profile to a Laravel web application using (Laravel Auth0 SDK).
auth0/login使用(Laravel Auth0 SDK)为Laravel Web应用添加登录、登出和用户个人功能。
auth0/loginPrerequisites
前提条件
- Laravel 11+ application
- PHP 8.2+ with extensions: ,
mbstring,openssljson - Composer installed
- Auth0 Regular Web Application configured (not an API - must be an Application)
- If you don't have Auth0 set up yet, use the skill first
auth0-quickstart
- Laravel 11+版本的应用
- PHP 8.2+版本,并安装以下扩展:、
mbstring、openssljson - 已安装Composer
- 已配置Auth0常规Web应用(不能是API,必须是应用类型)
- 如果您尚未设置Auth0,请先使用技能
auth0-quickstart
When NOT to Use
不适用场景
| Scenario | Use Instead |
|---|---|
| Laravel API with JWT Bearer validation | |
| Plain PHP (no framework) web app | |
| Plain PHP API | |
| Single Page Applications | |
| Next.js applications | |
| Node.js web apps | |
| Flask web apps | |
| 场景 | 替代方案 |
|---|---|
| 使用JWT Bearer验证的Laravel API | |
| 无框架的纯PHP Web应用 | |
| 纯PHP API | |
| 单页应用 | |
| Next.js应用 | |
| Node.js Web应用 | |
| Flask Web应用 | |
Quick Start Workflow
快速开始流程
1. Install SDK
1. 安装SDK
bash
composer require auth0/loginThe package requires (v8.19+) and will install it automatically. It also requires a PSR-18 HTTP client - if you don't already have one, install Guzzle:
auth0/loginauth0/auth0-phpbash
composer require guzzlehttp/guzzle guzzlehttp/psr7bash
composer require auth0/loginauth0/loginauth0/auth0-phpbash
composer require guzzlehttp/guzzle guzzlehttp/psr72. Publish Configuration
2. 发布配置文件
bash
php artisan vendor:publish --tag=auth0This creates with guard, middleware, and route configuration.
config/auth0.phpbash
php artisan vendor:publish --tag=auth0此命令会生成文件,包含Guard、中间件和路由配置。
config/auth0.php3. Configure Environment
3. 配置环境变量
Add to your :
.envbash
APP_URL=http://localhost:8000
AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_CLIENT_ID=your_client_id
AUTH0_CLIENT_SECRET=your_client_secret
AUTH0_AUDIENCE=https://your-api-identifier
AUTH0_REDIRECT_URI=${APP_URL}/callbackAUTH0_DOMAINhttps://AUTH0_CLIENT_IDAUTH0_CLIENT_SECRETAUTH0_AUDIENCEAPP_KEYImportant: Ensure includes the port if using the built-in dev server (). Fresh Laravel installs default to (no port) which causes callback URL mismatches.
APP_URLhttp://localhost:8000http://localhost添加到您的文件中:
.envbash
APP_URL=http://localhost:8000
AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_CLIENT_ID=your_client_id
AUTH0_CLIENT_SECRET=your_client_secret
AUTH0_AUDIENCE=https://your-api-identifier
AUTH0_REDIRECT_URI=${APP_URL}/callbackAUTH0_DOMAINhttps://AUTH0_CLIENT_IDAUTH0_CLIENT_SECRETAUTH0_AUDIENCEAPP_KEY重要提示:如果使用内置开发服务器,请确保包含端口(如)。全新安装的Laravel默认使用(不带端口),这会导致回调URL不匹配。
APP_URLhttp://localhost:8000http://localhost4. Configure Auth0 Dashboard
4. 配置Auth0控制台
In your Auth0 Application settings:
- Application Type: Regular Web Application
- Allowed Callback URLs:
http://localhost:8000/callback - Allowed Logout URLs:
http://localhost:8000
在您的Auth0应用设置中:
- 应用类型:常规Web应用
- 允许的回调URL:
http://localhost:8000/callback - 允许的登出URL:
http://localhost:8000
5. Configure Auth Guards
5. 配置认证Guard
Update to use Auth0 guards:
config/auth.phpphp
'guards' => [
'web' => [
'driver' => 'auth0.authenticator',
'provider' => 'auth0-provider',
'configuration' => 'web',
],
],
'providers' => [
'auth0-provider' => [
'driver' => 'auth0.provider',
'repository' => 'auth0.repository',
],
],The key maps to the guard definition in ( uses with session-based auth). We override the default guard so that Laravel's built-in middleware and work without specifying a guard name. The SDK also auto-registers an guard with identical config, but overriding is simpler.
configurationconfig/auth0.phpwebSTRATEGY_REGULARwebauthauth()->user()auth0-sessionweb更新以使用Auth0 Guard:
config/auth.phpphp
'guards' => [
'web' => [
'driver' => 'auth0.authenticator',
'provider' => 'auth0-provider',
'configuration' => 'web',
],
],
'providers' => [
'auth0-provider' => [
'driver' => 'auth0.provider',
'repository' => 'auth0.repository',
],
],configurationconfig/auth0.phpwebSTRATEGY_REGULARwebauthauth()->user()auth0-sessionwebweb6. Routes Are Auto-Registered
6. 路由自动注册
The SDK automatically registers these routes when is in :
registerAuthenticationRoutestrueconfig/auth0.php- - Redirects to Auth0 Universal Login
GET /login - - Handles OAuth callback, exchanges code for tokens
GET /callback - - Destroys session and redirects to Auth0 logout
GET /logout
No manual route definitions needed for the auth flow.
当中的设为时,SDK会自动注册以下路由:
config/auth0.phpregisterAuthenticationRoutestrue- - 重定向到Auth0通用登录页面
GET /login - - 处理OAuth回调,交换代码获取令牌
GET /callback - - 销毁会话并重定向到Auth0登出页面
GET /logout
无需手动定义认证流程的路由。
7. Add Protected Routes
7. 添加受保护路由
In :
routes/web.phpphp
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('home', ['user' => auth()->user()]);
});
Route::middleware('auth')->group(function () {
Route::get('/profile', function () {
return view('profile', ['user' => auth()->user()]);
});
});The standard middleware works with the Auth0 guard. Unauthenticated users are redirected to .
auth/login在中:
routes/web.phpphp
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('home', ['user' => auth()->user()]);
});
Route::middleware('auth')->group(function () {
Route::get('/profile', function () {
return view('profile', ['user' => auth()->user()]);
});
});标准的中间件可与Auth0 Guard配合使用。未认证用户会被重定向到。
auth/login8. Create Views
8. 创建视图
Create :
resources/views/home.blade.phpblade
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
@if($user)
<h1>Welcome, {{ $user->name }}!</h1>
<p><a href="/profile">Profile</a></p>
<p><a href="/logout">Logout</a></p>
@else
<h1>Welcome</h1>
<p><a href="/login">Login</a></p>
@endif
</body>
</html>Create :
resources/views/profile.blade.phpblade
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Profile</title>
</head>
<body>
<h1>{{ $user->name }}</h1>
<p>Email: {{ $user->email }}</p>
<img src="{{ $user->picture }}" alt="avatar" width="100" />
<hr>
<h2>User Claims</h2>
<pre>{{ json_encode($user->jsonSerialize(), JSON_PRETTY_PRINT) }}</pre>
<p><a href="/">Home</a> | <a href="/logout">Logout</a></p>
</body>
</html>创建:
resources/views/home.blade.phpblade
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
@if($user)
<h1>Welcome, {{ $user->name }}!</h1>
<p><a href="/profile">Profile</a></p>
<p><a href="/logout">Logout</a></p>
@else
<h1>Welcome</h1>
<p><a href="/login">Login</a></p>
@endif
</body>
</html>创建:
resources/views/profile.blade.phpblade
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Profile</title>
</head>
<body>
<h1>{{ $user->name }}</h1>
<p>Email: {{ $user->email }}</p>
<img src="{{ $user->picture }}" alt="avatar" width="100" />
<hr>
<h2>User Claims</h2>
<pre>{{ json_encode($user->jsonSerialize(), JSON_PRETTY_PRINT) }}</pre>
<p><a href="/">Home</a> | <a href="/logout">Logout</a></p>
</body>
</html>9. Test Authentication
9. 测试认证功能
bash
php artisan serveVisit and click Login.
http://localhost:8000Important: Always access the app via (not ). The callback URL uses , so the session cookie must be set for to persist across the Auth0 login redirect. Using causes an "Invalid state" error because the session cookie won't be sent to the callback URL.
http://localhost:8000http://127.0.0.1:8000localhostlocalhost127.0.0.1localhostbash
php artisan serve访问并点击登录。
http://localhost:8000重要提示:请始终通过访问应用(不要使用)。回调URL使用,因此会话Cookie必须针对设置,才能在Auth0登录重定向后保持有效。使用会导致“无效状态”错误,因为会话Cookie不会发送到回调URL。
http://localhost:8000http://127.0.0.1:8000localhostlocalhost127.0.0.1localhostCommon Mistakes
常见错误
| Mistake | Fix |
|---|---|
Using | Use |
| App created as SPA type in Auth0 Dashboard | Must be Regular Web Application for server-side session auth |
| Missing callback URL in Auth0 Dashboard | Add |
| Missing logout URL in Auth0 Dashboard | Add |
| Not publishing the config | Run |
| Using wrong guard driver name | Driver is |
Forgetting to set | Run |
Calling | Use Laravel's |
Manually defining | Routes are auto-registered by the service provider |
Setting | Use bare domain: |
Using | Only available in routes with the |
Missing | Without an audience, Auth0 returns opaque tokens the SDK cannot parse - causes "JWT string must contain two dots" crash |
Visiting | Session cookies set for |
Using | |
| 错误操作 | 修复方案 |
|---|---|
在Laravel中直接使用 | 使用 |
| 在Auth0控制台中创建SPA类型的应用 | 必须使用常规Web应用类型才能支持服务端会话认证 |
| Auth0控制台中未添加回调URL | 将 |
| Auth0控制台中未添加登出URL | 将 |
| 未发布配置文件 | 在配置前执行 |
| 使用错误的Guard驱动名称 | 驱动名称应为 |
忘记设置 | 执行 |
直接调用 | 使用Laravel的 |
手动定义 | 路由由服务提供者自动注册 |
| 使用纯域名: |
未使用中间件就调用 | 仅在应用了 |
缺少 | 未设置受众时,Auth0会返回无法被SDK解析的不透明令牌——导致“JWT字符串必须包含两个点”错误 |
访问 | 针对 |
使用 | |
Key SDK Methods
SDK核心方法
| Method | Usage | Purpose |
|---|---|---|
| In routes/controllers | Returns the authenticated |
| In routes/controllers/views | Returns |
| When using multiple guards | Gets a specific Auth0 guard instance |
| On user object | User's display name (via |
| On user object | User's email (via |
| On user object | User's avatar URL (via |
| On user object | Returns the Auth0 |
| On user object | Returns any claim value explicitly |
| On user object | Returns all user claims as array |
| 方法 | 使用场景 | 用途 |
|---|---|---|
| 路由/控制器中 | 返回已认证的 |
| 路由/控制器/视图中 | 用户已认证时返回 |
| 使用多个Guard时 | 获取指定的Auth0 Guard实例 |
| 用户对象上 | 用户显示名称(通过 |
| 用户对象上 | 用户邮箱(通过 |
| 用户对象上 | 用户头像URL(通过 |
| 用户对象上 | 返回Auth0的 |
| 用户对象上 | 显式返回任意声明的值 |
| 用户对象上 | 返回所有用户声明的数组形式 |
User Object
用户对象
The authenticated user is a instance implementing Laravel's contract. It uses magic for property-style access to claims:
StatefulUserAuthenticatable__getphp
$user = auth()->user();
$user->name; // display name (via __get)
$user->email; // email address (via __get)
$user->picture; // avatar URL (via __get)
$user->email_verified; // any claim via property access
$user->getAuthIdentifier(); // Auth0 'sub' (e.g. 'auth0|abc123')
$user->getAttribute('sub'); // explicit claim access
$user->jsonSerialize(); // all claims as arrayAccess any ID token claim as a property: , , , etc. For explicit access, use .
$user->nickname$user->updated_at$user->sub$user->getAttribute('claim_name')已认证用户是实例,实现了Laravel的契约。它使用魔术方法以属性方式访问声明:
StatefulUserAuthenticatable__getphp
$user = auth()->user();
$user->name; // 显示名称(通过__get)
$user->email; // 邮箱地址(通过__get)
$user->picture; // 头像URL(通过__get)
$user->email_verified; // 通过属性访问任意声明
$user->getAuthIdentifier(); // Auth0 'sub'(例如 'auth0|abc123')
$user->getAttribute('sub'); // 显式访问声明
$user->jsonSerialize(); // 所有声明的数组形式可以通过属性访问任何ID令牌声明:、、等。如需显式访问,使用。
$user->nickname$user->updated_at$user->sub$user->getAttribute('claim_name')Related Skills
相关技能
- - Protect Laravel API routes with JWT Bearer token validation
auth0-laravel-api - - Plain PHP web apps without a framework
auth0-php - - Initial Auth0 setup
auth0-quickstart - - Add Multi-Factor Authentication
auth0-mfa - - Manage Auth0 resources from the terminal
auth0-cli
- - 使用JWT Bearer令牌验证保护Laravel API路由
auth0-laravel-api - - 无框架的纯PHP Web应用
auth0-php - - 初始化Auth0设置
auth0-quickstart - - 添加多因素认证
auth0-mfa - - 通过终端管理Auth0资源
auth0-cli
Quick Reference
快速参考
Guard configuration ():
config/auth.phpphp
'guards' => [
'web' => [
'driver' => 'auth0.authenticator',
'provider' => 'auth0-provider',
'configuration' => 'web',
],
],
'providers' => [
'auth0-provider' => [
'driver' => 'auth0.provider',
'repository' => 'auth0.repository',
],
],Route protection:
php
Route::middleware('auth')->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
});Check auth in Blade:
blade
@auth
<p>Hello, {{ auth()->user()->name }}</p>
@else
<a href="/login">Login</a>
@endauthEnvironment variables:
- - Application URL with port (e.g.
APP_URL)http://localhost:8000 - - Auth0 tenant domain (e.g.
AUTH0_DOMAIN)tenant.us.auth0.com - - Application client ID
AUTH0_CLIENT_ID - - Application client secret
AUTH0_CLIENT_SECRET - - API identifier (required for JWT access tokens)
AUTH0_AUDIENCE - - Callback URL (defaults to
AUTH0_REDIRECT_URI)${APP_URL}/callback - - Laravel app key, used as cookie encryption secret
APP_KEY
Guard配置():
config/auth.phpphp
'guards' => [
'web' => [
'driver' => 'auth0.authenticator',
'provider' => 'auth0-provider',
'configuration' => 'web',
],
],
'providers' => [
'auth0-provider' => [
'driver' => 'auth0.provider',
'repository' => 'auth0.repository',
],
],路由保护:
php
Route::middleware('auth')->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
});Blade中检查认证状态:
blade
@auth
<p>Hello, {{ auth()->user()->name }}</p>
@else
<a href="/login">Login</a>
@endauth环境变量:
- - 应用URL(包含端口,例如
APP_URL)http://localhost:8000 - - Auth0租户域名(例如
AUTH0_DOMAIN)tenant.us.auth0.com - - 应用客户端ID
AUTH0_CLIENT_ID - - 应用客户端密钥
AUTH0_CLIENT_SECRET - - API标识符(获取JWT访问令牌必需)
AUTH0_AUDIENCE - - 回调URL(默认值为
AUTH0_REDIRECT_URI)${APP_URL}/callback - - Laravel应用密钥,用作Cookie加密密钥
APP_KEY
Detailed Documentation
详细文档
- Setup Guide - Automated setup scripts, environment configuration, Auth0 CLI usage
- Integration Guide - Scope checking, calling APIs, events, custom user models, session management
- API Reference - Complete guard API, configuration options, user model methods
- 设置指南 - 自动化设置脚本、环境配置、Auth0 CLI使用方法
- 集成指南 - 权限范围检查、API调用、事件、自定义用户模型、会话管理
- API参考 - 完整的Guard API、配置选项、用户模型方法