auth0-laravel-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 Laravel API Integration
Auth0 Laravel API 集成
Protect Laravel API endpoints with JWT access token validation using and the .
auth0/loginAuthorizationGuard使用和,通过JWT访问令牌验证来保护Laravel API端点。
auth0/loginAuthorizationGuardPrerequisites
前置条件
- Laravel 11+ application
- PHP 8.2+ with extensions: ,
mbstring,openssljson - Composer installed
- Auth0 API resource configured (not an Application - must be an API)
- If you don't have Auth0 set up yet, use the skill first
auth0-quickstart
- Laravel 11+ 应用
- PHP 8.2+ 及扩展:、
mbstring、openssljson - 已安装Composer
- 已配置Auth0 API资源(不是应用程序,必须是API)
- 如果尚未设置Auth0,请先使用技能
auth0-quickstart
When NOT to Use
不适用于以下场景
| Scenario | Use Instead |
|---|---|
| Laravel web app with login/logout UI | |
| Plain PHP API (no framework) | |
| Plain PHP web app | |
| Single Page Applications | |
| FastAPI / Python APIs | |
| Express / Node.js APIs | |
| Issuing tokens | This skill is for validating access tokens, not issuing them |
| 场景 | 替代方案 |
|---|---|
| 带登录/登出UI的Laravel Web应用 | |
| 无框架的纯PHP API | |
| 纯PHP Web应用 | |
| 单页应用 | |
| FastAPI / Python API | |
| Express / Node.js API | |
| 颁发令牌 | 本技能仅用于验证访问令牌,不负责颁发令牌 |
Quick Start Workflow
快速开始流程
1. Install SDK
1. 安装SDK
bash
composer require auth0/loginThe package requires (v8.19+) and installs it automatically. It also requires a PSR-18 HTTP client - if you don't already have one:
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这会创建文件,包含守卫、中间件和路由配置。
config/auth0.php3. Create Auth0 API
3. 创建Auth0 API
You need an API (not Application) in Auth0.
STOP - ask the user before proceeding.Ask exactly this question and wait for their answer before doing anything else:"How would you like to create the Auth0 API resource?
- Automated - I'll run Auth0 CLI scripts that create the resource and write the exact values to your
automatically..env- Manual - You create the API yourself in the Auth0 Dashboard (or via
) and provide me the Domain and Audience.auth0 apis createWhich do you prefer? (1 = Automated / 2 = Manual)"Do NOT proceed to any setup steps until the user has answered. Do NOT default to manual.
If the user chose Automated, follow the Setup Guide for complete CLI scripts. The automated path writes for you - skip Step 4 below and proceed directly to Step 5.
.envIf the user chose Manual, follow the Setup Guide (Manual Setup section) for full instructions. Then continue with Step 4 below.
Quick reference for manual API creation:
bash
auth0 apis create \
--name "My Laravel API" \
--identifier https://my-api.example.com \
--jsonOr create manually in Auth0 Dashboard -> Applications -> APIs
你需要在Auth0中创建一个API(不是应用程序)。
暂停 - 继续前请询问用户。请准确询问以下问题,等待用户回复后再执行其他操作:"你希望如何创建Auth0 API资源?
- 自动创建 - 我会运行Auth0 CLI脚本创建资源,并自动将准确值写入你的
文件。.env- 手动创建 - 你在Auth0控制台自行创建API(或通过
命令),并提供域名和受众。auth0 apis create你选择哪种方式?(1=自动 / 2=手动)"在用户回复前,请勿进行任何设置步骤。请勿默认选择手动方式。
如果用户选择自动创建,请遵循设置指南中的完整CLI脚本。自动方式会为你写入文件 - 跳过下方步骤4,直接进行步骤5。
.env如果用户选择手动创建,请遵循设置指南(手动设置部分)中的完整说明。然后继续步骤4。
手动创建API的快速参考命令:
bash
auth0 apis create \
--name "My Laravel API" \
--identifier https://my-api.example.com \
--json或在Auth0控制台 -> 应用程序 -> API中手动创建
4. Configure Environment
4. 配置环境变量
Add to your :
.envbash
AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.comAUTH0_DOMAINhttps://AUTH0_AUDIENCE在中添加:
.envbash
AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.comAUTH0_DOMAINhttps://AUTH0_AUDIENCE5. Configure Auth Guard
5. 配置认证守卫
Update to add the API guard:
config/auth.phpphp
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'auth0-api' => [
'driver' => 'auth0.authorizer',
'provider' => 'auth0-provider',
'configuration' => 'api',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'auth0-provider' => [
'driver' => 'auth0.provider',
'repository' => 'auth0.repository',
],
],Key points:
- must be
driver(notauth0.authorizerwhich is for web apps)auth0.authenticator - must be
configurationwhich maps to the'api'guard inapiconfig/auth0.php - The SDK auto-registers an guard with this config, but defining it explicitly is clearer
auth0-api
更新以添加API守卫:
config/auth.phpphp
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'auth0-api' => [
'driver' => 'auth0.authorizer',
'provider' => 'auth0-provider',
'configuration' => 'api',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'auth0-provider' => [
'driver' => 'auth0.provider',
'repository' => 'auth0.repository',
],
],关键点:
- 必须为
driver(不是用于Web应用的auth0.authorizer)auth0.authenticator - 必须为
configuration,对应'api'中的config/auth0.php守卫api - SDK会自动注册带有此配置的守卫,但显式定义更清晰
auth0-api
6. Verify Auth0 Config
6. 验证Auth0配置
After publishing, verify that contains a key with set to (value: ). This is already present in the published config — no manual editing needed.
config/auth0.phpguards.apistrategySdkConfiguration::STRATEGY_API'api'The published file uses class constants for keys (e.g., ), which resolve to the same string values at runtime:
Configuration::CONFIG_STRATEGYphp
'guards' => [
'api' => [
'strategy' => SdkConfiguration::STRATEGY_API, // value: 'api'
],
],The published config also includes and guard sections — these can be ignored for API-only usage. The strategy disables all session/cookie machinery and enables stateless Bearer token validation.
defaultwebSTRATEGY_API发布配置后,验证中是否包含键,且设置为(值为)。发布的配置文件中已默认包含此设置,无需手动编辑。
config/auth0.phpguards.apistrategySdkConfiguration::STRATEGY_API'api'发布的文件使用类常量作为键(例如),运行时会解析为相同的字符串值:
Configuration::CONFIG_STRATEGYphp
'guards' => [
'api' => [
'strategy' => SdkConfiguration::STRATEGY_API, // 值:'api'
],
],发布的配置文件还包含和守卫部分 - 仅API使用场景下可忽略这些。策略会禁用所有会话/ cookie机制,启用无状态Bearer令牌验证。
defaultwebSTRATEGY_API7. Add Protected API Routes
7. 添加受保护的API路由
Laravel 11+ does not include by default. If the file does not exist, scaffold it:
routes/api.phpbash
php artisan install:apiThis creates and registers it in with the prefix. It also installs Laravel Sanctum, which is unused but harmless alongside Auth0.
routes/api.phpbootstrap/app.php/apiIn :
routes/api.phpphp
use Illuminate\Support\Facades\Route;
Route::get('/public', function () {
return response()->json(['message' => 'Public endpoint - no authentication required']);
});
Route::middleware('auth:auth0-api')->group(function () {
Route::get('/private', function () {
$user = auth('auth0-api')->user();
return response()->json([
'message' => 'Private endpoint',
'sub' => $user->getAuthIdentifier(),
]);
});
});The middleware validates the Bearer token, verifies the signature against the JWKS endpoint, and checks issuer and audience claims. Requests without a valid token receive a 401 response.
auth:auth0-apiLaravel 11+ 默认不包含。如果该文件不存在,生成它:
routes/api.phpbash
php artisan install:api这会创建并在中注册,前缀为。同时会安装Laravel Sanctum,它在Auth0旁边是无用但无害的。
routes/api.phpbootstrap/app.php/api在中:
routes/api.phpphp
use Illuminate\Support\Facades\Route;
Route::get('/public', function () {
return response()->json(['message' => '公开端点 - 无需认证']);
});
Route::middleware('auth:auth0-api')->group(function () {
Route::get('/private', function () {
$user = auth('auth0-api')->user();
return response()->json([
'message' => '私有端点',
'sub' => $user->getAuthIdentifier(),
]);
});
});auth:auth0-api8. Scope and Permission Checks
8. 权限范围和权限检查
Use the guard's and methods:
hasScope()hasPermission()php
Route::middleware('auth:auth0-api')->group(function () {
Route::get('/messages', function () {
$guard = auth('auth0-api');
if (!$guard->hasScope('read:messages')) {
return response()->json(['error' => 'insufficient_scope'], 403);
}
return response()->json(['messages' => []]);
});
Route::delete('/users/{id}', function (string $id) {
$guard = auth('auth0-api');
if (!$guard->hasPermission('delete:users')) {
return response()->json(['error' => 'insufficient_permissions'], 403);
}
return response()->json(['deleted' => $id]);
});
});- checks the
hasScope()claim (space-separated string in the JWT)scope - checks the
hasPermission()claim (array, requires RBAC enabled on the API in Auth0 Dashboard)permissions
使用守卫的和方法:
hasScope()hasPermission()php
Route::middleware('auth:auth0-api')->group(function () {
Route::get('/messages', function () {
$guard = auth('auth0-api');
if (!$guard->hasScope('read:messages')) {
return response()->json(['error' => 'insufficient_scope'], 403);
}
return response()->json(['messages' => []]);
});
Route::delete('/users/{id}', function (string $id) {
$guard = auth('auth0-api');
if (!$guard->hasPermission('delete:users')) {
return response()->json(['error' => 'insufficient_permissions'], 403);
}
return response()->json(['deleted' => $id]);
});
});- 检查
hasScope()声明(JWT中的空格分隔字符串)scope - 检查
hasPermission()声明(数组,需要在Auth0控制台的API中启用RBAC)permissions
9. Access Token Claims
9. 访问令牌声明
The authenticated user is a instance with dynamic claim access:
StatelessUserphp
Route::middleware('auth:auth0-api')->get('/profile', function () {
$user = auth('auth0-api')->user();
return response()->json([
'sub' => $user->getAuthIdentifier(),
'email' => $user->email,
'permissions' => $user->permissions ?? [],
'all_claims' => $user->jsonSerialize(),
]);
});Claims are accessed via:
- - Returns
$user->getAuthIdentifier()claimsub - - Dynamic property access via
$user->claim_name__get - - Explicit access
$user->getAttribute('claim_name') - - All claims as array
$user->jsonSerialize()
已认证用户是实例,可动态访问声明:
StatelessUserphp
Route::middleware('auth:auth0-api')->get('/profile', function () {
$user = auth('auth0-api')->user();
return response()->json([
'sub' => $user->getAuthIdentifier(),
'email' => $user->email,
'permissions' => $user->permissions ?? [],
'all_claims' => $user->jsonSerialize(),
]);
});声明可通过以下方式访问:
- - 返回
$user->getAuthIdentifier()声明sub - - 通过
$user->claim_name动态访问属性__get - - 显式访问
$user->getAttribute('claim_name') - - 以数组形式返回所有声明
$user->jsonSerialize()
10. Test the API
10. 测试API
Agent instruction: Start the Laravel dev server and verify the basic endpoints work without credentials:bashphp artisan serve & sleep 2 curl -s -H "Accept: application/json" http://localhost:8000/api/public curl -s -o /dev/null -w "%{http_code}" -H "Accept: application/json" http://localhost:8000/api/private
should return/api/public{"message":"Public endpoint - no authentication required"} should return HTTP 401/api/privateImportant: Theheader is required. Without it, Laravel's-H "Accept: application/json"middleware returns a 302 redirect instead of 401.AuthenticateIf both pass, the guard is working. Kill the background server when done:bashkill %1 2>/dev/nullFailcheck: If the server fails to start or responses are unexpected, check thatexists andconfig/auth0.phphas.envandAUTH0_DOMAINset. After 5-6 failed iterations, useAUTH0_AUDIENCE.AskUserQuestion
Agent instruction: STOP - ask after basic tests pass.Once public/401 tests pass, ask the user:"Your API is set up and the guard is working (public returns 200, private returns 401 without a token). Would you like me to help you set up testing with a real access token?
- Yes - I'll help you configure an M2M application to get test tokens.
- No - I'm done for now.
Which do you prefer?"Do NOT proceed with M2M/token setup unless the user says yes.
Agent instruction (M2M app setup - only if user wants testing):If the user chose to set up testing, ask:"To test your protected endpoints, you need a Machine-to-Machine (M2M) application authorized to request tokens for this API.
- Create new - I'll create a new M2M application and authorize it for this API.
- Use existing - You already have an M2M application. Provide the Client ID and I'll authorize it for this API.
Which do you prefer? (1 = Create new / 2 = Use existing)"Do NOT proceed until the user answers.If the user chose "Create new":bashauth0 apps create \ --name "${PWD##*/} (Test App)" \ --type m2m \ --no-input --jsonParse JSON withto extractjq. Do NOT useclient_id. Then create a client grant:--reveal-secretsbashauth0 api post "client-grants" --data '{ "client_id": "<CLIENT_ID>", "audience": "<API_IDENTIFIER>", "scope": ["<SCOPES>"] }'If the user chose "Use existing": Ask for Client ID. Create a client grant (409 conflict = already authorized, fine).
Agent instruction (TOKEN ISOLATION - CRITICAL):The agent MUST NEVER directly see or display access token values.
- Do NOT run
on its ownauth0 test token- Do NOT ask the user to paste their token
- Do NOT echo or store the token value
Secure testing (single-command chain):bashphp artisan serve & sleep 2 TEST_TOKEN=$(auth0 test token <M2M_CLIENT_ID> --audience <AUDIENCE> --scopes <SCOPE1,SCOPE2> 2>/dev/null | grep -o 'ey[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*') && \ [ -n "$TEST_TOKEN" ] && echo "Token acquired (${#TEST_TOKEN} chars)" && \ curl -s -H "Accept: application/json" -H "Authorization: Bearer $TEST_TOKEN" http://localhost:8000/api/private kill %1 2>/dev/nullIf the user does NOT ask to test, provide commands for them to run manually:bashauth0 test token <CLIENT_ID> --audience <AUDIENCE> --scopes <SCOPE1,SCOPE2> curl -H "Accept: application/json" -H "Authorization: Bearer <PASTE_TOKEN_HERE>" http://localhost:8000/api/private
Start the server:
bash
php artisan serveTest public endpoint (no token needed):
bash
curl -H "Accept: application/json" http://localhost:8000/api/publicTest protected endpoint without token (should return 401):
bash
curl -H "Accept: application/json" http://localhost:8000/api/privateNote: The header is required. Without it, Laravel redirects (302) instead of returning 401.
Accept: application/jsonTest protected endpoint with token:
bash
curl http://localhost:8000/api/private \
-H "Accept: application/json" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"Get a test token via Auth0 Dashboard -> APIs -> Test tab, or via the M2M flow described above.
Agent指令: 启动Laravel开发服务器,验证基础端点在无凭据情况下是否正常工作:bashphp artisan serve & sleep 2 curl -s -H "Accept: application/json" http://localhost:8000/api/public curl -s -o /dev/null -w "%{http_code}" -H "Accept: application/json" http://localhost:8000/api/private
应返回/api/public{"message":"公开端点 - 无需认证"} 应返回HTTP 401/api/private重要提示: 必须携带请求头。如果没有,Laravel的-H "Accept: application/json"中间件会返回302重定向而非401。Authenticate如果两项测试都通过,说明守卫工作正常。完成后关闭后台服务器:bashkill %1 2>/dev/null故障检查: 如果服务器无法启动或响应异常,请检查是否存在,以及config/auth0.php中是否设置了.env和AUTH0_DOMAIN。经过5-6次失败尝试后,使用AUTH0_AUDIENCE询问用户。AskUserQuestion
Agent指令:基础测试通过后暂停并询问用户。当公开端点返回200、私有端点无令牌时返回401的测试通过后,询问用户:"你的API已设置完成,守卫工作正常(公开端点返回200,无令牌时私有端点返回401)。你需要我帮助你设置使用真实访问令牌的测试吗?
- 是 - 我会帮你配置M2M应用以获取测试令牌。
- 否 - 我已完成当前操作。
你选择哪种?"除非用户选择是,否则请勿进行M2M/令牌设置。
Agent指令(仅当用户需要测试时进行M2M应用设置):如果用户选择设置测试,请询问:"要测试受保护的端点,你需要一个被授权为此API请求令牌的机器对机器(M2M)应用。
- 创建新应用 - 我会创建一个新的M2M应用并授权它访问此API。
- 使用现有应用 - 你已有M2M应用,请提供客户端ID,我会授权它访问此API。
你选择哪种?(1=创建新应用 / 2=使用现有应用)"用户回复前请勿继续。如果用户选择“创建新应用”:bashauth0 apps create \ --name "${PWD##*/} (Test App)" \ --type m2m \ --no-input --json使用解析JSON提取jq。请勿使用client_id。 然后创建客户端授权:--reveal-secretsbashauth0 api post "client-grants" --data '{ "client_id": "<CLIENT_ID>", "audience": "<API_IDENTIFIER>", "scope": ["<SCOPES>"] }'如果用户选择“使用现有应用”: 请求用户提供客户端ID。创建客户端授权(返回409冲突表示已授权,无需处理)。
Agent指令(令牌隔离 - 关键要求):Agent绝对不能直接查看或显示访问令牌值。
- 请勿单独运行
auth0 test token- 请勿要求用户粘贴令牌
- 请勿回显或存储令牌值
安全测试(单命令链):bashphp artisan serve & sleep 2 TEST_TOKEN=$(auth0 test token <M2M_CLIENT_ID> --audience <AUDIENCE> --scopes <SCOPE1,SCOPE2> 2>/dev/null | grep -o 'ey[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*') && \ [ -n "$TEST_TOKEN" ] && echo "已获取令牌(${#TEST_TOKEN} 字符)" && \ curl -s -H "Accept: application/json" -H "Authorization: Bearer $TEST_TOKEN" http://localhost:8000/api/private kill %1 2>/dev/null如果用户不要求测试,提供手动运行的命令:bashauth0 test token <CLIENT_ID> --audience <AUDIENCE> --scopes <SCOPE1,SCOPE2> curl -H "Accept: application/json" -H "Authorization: Bearer <PASTE_TOKEN_HERE>" http://localhost:8000/api/private
启动服务器:
bash
php artisan serve测试公开端点(无需令牌):
bash
curl -H "Accept: application/json" http://localhost:8000/api/public测试无令牌的受保护端点(应返回401):
bash
curl -H "Accept: application/json" http://localhost:8000/api/private注意:必须携带请求头。如果没有,Laravel会返回302重定向而非401。
Accept: application/json使用令牌测试受保护端点:
bash
curl http://localhost:8000/api/private \
-H "Accept: application/json" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"可通过Auth0控制台 -> API -> 测试标签,或上述M2M流程获取测试令牌。
Common Mistakes
常见错误
| Mistake | Fix |
|---|---|
Using | API guard must use |
Using | Use |
| Created an Application instead of an API in Auth0 | Must create an API resource (Dashboard -> Applications -> APIs) |
Passing | Use bare domain: |
Using | Use |
| Not publishing config | Run |
Missing | Required for token validation - without it, tokens can't be verified against the correct audience |
Using | Defaults to the |
Checking | The |
Calling | Must enable "Add Permissions in the Access Token" in Auth0 Dashboard -> APIs -> Settings |
| Using ID tokens for API auth | Must use access tokens - ID tokens are for the client app |
Setting | Must be |
Testing with | Laravel returns 302 redirect instead of 401 - always send |
| Scopes must be defined on the API resource in Auth0 Dashboard - requesting a scope in the token request does not grant it unless defined |
| RBAC permissions are only embedded in tokens from user-based flows (Authorization Code), not client-credentials grants |
| Run |
| 错误 | 修复方案 |
|---|---|
API路由使用 | API守卫必须使用 |
API路由使用 | 使用 |
| 在Auth0中创建了应用程序而非API | 必须创建API资源(控制台 -> 应用程序 -> API) |
| 使用裸域名: |
直接使用 | 使用 |
| 未发布配置文件 | 配置前运行 |
| 令牌验证必需 - 没有它,无法针对正确的受众验证令牌 |
未指定守卫名称使用 | 默认使用 |
将 | JWT中的 |
未启用RBAC就调用 | 必须在Auth0控制台 -> API -> 设置中启用“在访问令牌中添加权限” |
| 使用ID令牌进行API认证 | 必须使用访问令牌 - ID令牌用于客户端应用 |
API守卫设置 | 必须设置为 |
使用 | Laravel返回302重定向而非401 - API请求始终携带 |
对未在API上定义的权限范围, | 权限范围必须在Auth0控制台的API资源上定义 - 令牌请求中请求权限范围不会自动授予,除非已定义 |
M2M令牌下 | RBAC权限仅嵌入来自用户流(授权码)的令牌,不包含在客户端凭证授予的令牌中 |
Laravel 11+中缺少 | 运行 |
Key SDK Methods
关键SDK方法
| Method | Returns | Purpose |
|---|---|---|
| | Returns authenticated user or |
| | Whether request has a valid token |
| | Check if token has a specific scope |
| | Check if token has a specific RBAC permission |
| | Returns the |
| | Returns |
| | Returns any claim value |
| | Returns all claims as array |
| | Full credential with decoded token data |
| 方法 | 返回值 | 用途 |
|---|---|---|
| | 返回已认证用户或 |
| | 请求是否带有有效令牌 |
| | 检查令牌是否包含特定权限范围 |
| | 检查令牌是否包含特定RBAC权限 |
| | 直接返回 |
| | 返回 |
| | 返回任意声明值 |
| | 以数组形式返回所有声明 |
| | 包含解码令牌数据的完整凭证 |
Related Skills
相关技能
- - For Laravel web apps with login/logout using session-based auth
auth0-laravel - - For plain PHP APIs without Laravel
auth0-php-api - - Initial Auth0 setup
auth0-quickstart - - Add Multi-Factor Authentication
auth0-mfa - - Manage Auth0 resources from the terminal
auth0-cli
- - 用于带登录/登出的Laravel Web应用,基于会话认证
auth0-laravel - - 用于无Laravel的纯PHP API
auth0-php-api - - 初始Auth0设置
auth0-quickstart - - 添加多因素认证
auth0-mfa - - 从终端管理Auth0资源
auth0-cli
Quick Reference
快速参考
Guard configuration ():
config/auth.phpphp
'guards' => [
'auth0-api' => [
'driver' => 'auth0.authorizer',
'provider' => 'auth0-provider',
'configuration' => 'api',
],
],
'providers' => [
'auth0-provider' => [
'driver' => 'auth0.provider',
'repository' => 'auth0.repository',
],
],Route protection:
php
Route::middleware('auth:auth0-api')->group(function () {
Route::get('/resource', fn() => response()->json([...]));
});Scope/permission checks:
php
$guard = auth('auth0-api');
$guard->hasScope('read:messages'); // checks scope claim
$guard->hasPermission('delete:users'); // checks permissions claim (RBAC)User claims:
php
$user = auth('auth0-api')->user();
$user->getAuthIdentifier(); // sub
$user->email; // any claim via __get
$user->getAttribute('iss'); // explicit claim accessEnvironment variables:
- - Auth0 tenant domain (e.g.
AUTH0_DOMAIN)tenant.us.auth0.com - - API identifier (e.g.
AUTH0_AUDIENCE)https://api.example.com
Common Use Cases:
- Protect routes -> middleware (see Step 7)
auth:auth0-api - Scope enforcement -> (see Step 8)
hasScope() - Permission enforcement -> (see Step 8)
hasPermission() - Advanced configuration -> API Reference
守卫配置():
config/auth.phpphp
'guards' => [
'auth0-api' => [
'driver' => 'auth0.authorizer',
'provider' => 'auth0-provider',
'configuration' => 'api',
],
],
'providers' => [
'auth0-provider' => [
'driver' => 'auth0.provider',
'repository' => 'auth0.repository',
],
],路由保护:
php
Route::middleware('auth:auth0-api')->group(function () {
Route::get('/resource', fn() => response()->json([...]));
});权限范围/权限检查:
php
$guard = auth('auth0-api');
$guard->hasScope('read:messages'); // 检查scope声明
$guard->hasPermission('delete:users'); // 检查permissions声明(RBAC)用户声明:
php
$user = auth('auth0-api')->user();
$user->getAuthIdentifier(); // sub
$user->email; // 通过__get访问任意声明
$user->getAttribute('iss'); // 显式访问声明环境变量:
- - Auth0租户域名(例如
AUTH0_DOMAIN)tenant.us.auth0.com - - API标识符(例如
AUTH0_AUDIENCE)https://api.example.com
常见用例:
- 保护路由 -> 中间件(见步骤7)
auth:auth0-api - 权限范围强制 -> (见步骤8)
hasScope() - 权限强制 -> (见步骤8)
hasPermission() - 高级配置 -> API参考
Detailed Documentation
详细文档
- Setup Guide - Auth0 CLI setup, environment configuration, getting test tokens
- Integration Guide - Scopes, permissions, CORS, custom user repositories, error handling, multi-guard
- API Reference - Complete AuthorizationGuard API, StatelessUser, CredentialEntity, configuration options
- 设置指南 - Auth0 CLI设置、环境配置、获取测试令牌
- 集成指南 - 权限范围、权限、CORS、自定义用户仓库、错误处理、多守卫
- API参考 - 完整的AuthorizationGuard API、StatelessUser、CredentialEntity、配置选项