auth0-laravel-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 Laravel API Integration

Auth0 Laravel API 集成

Protect Laravel API endpoints with JWT access token validation using
auth0/login
and the
AuthorizationGuard
.

使用
auth0/login
AuthorizationGuard
,通过JWT访问令牌验证来保护Laravel API端点。

Prerequisites

前置条件

  • Laravel 11+ application
  • PHP 8.2+ with extensions:
    mbstring
    ,
    openssl
    ,
    json
  • Composer installed
  • Auth0 API resource configured (not an Application - must be an API)
  • If you don't have Auth0 set up yet, use the
    auth0-quickstart
    skill first
  • Laravel 11+ 应用
  • PHP 8.2+ 及扩展:
    mbstring
    openssl
    json
  • 已安装Composer
  • 已配置Auth0 API资源(不是应用程序,必须是API)
  • 如果尚未设置Auth0,请先使用
    auth0-quickstart
    技能

When NOT to Use

不适用于以下场景

ScenarioUse Instead
Laravel web app with login/logout UI
auth0-laravel
(session-based
AuthenticationGuard
)
Plain PHP API (no framework)
auth0-php-api
Plain PHP web app
auth0-php
Single Page Applications
auth0-react
,
auth0-vue
, or
auth0-angular
FastAPI / Python APIs
auth0-fastapi-api
Express / Node.js APIs
express-oauth2-jwt-bearer
Issuing tokensThis skill is for validating access tokens, not issuing them

场景替代方案
带登录/登出UI的Laravel Web应用
auth0-laravel
(基于会话的
AuthenticationGuard
无框架的纯PHP API
auth0-php-api
纯PHP Web应用
auth0-php
单页应用
auth0-react
auth0-vue
auth0-angular
FastAPI / Python API
auth0-fastapi-api
Express / Node.js API
express-oauth2-jwt-bearer
颁发令牌本技能仅用于验证访问令牌,不负责颁发令牌

Quick Start Workflow

快速开始流程

1. Install SDK

1. 安装SDK

bash
composer require auth0/login
The
auth0/login
package requires
auth0/auth0-php
(v8.19+) and installs it automatically. It also requires a PSR-18 HTTP client - if you don't already have one:
bash
composer require guzzlehttp/guzzle guzzlehttp/psr7
bash
composer require auth0/login
auth0/login
包依赖
auth0/auth0-php
(v8.19+),会自动安装。它还需要PSR-18 HTTP客户端,如果尚未安装:
bash
composer require guzzlehttp/guzzle guzzlehttp/psr7

2. Publish Configuration

2. 发布配置文件

bash
php artisan vendor:publish --tag=auth0
This creates
config/auth0.php
with guard, middleware, and route configuration.
bash
php artisan vendor:publish --tag=auth0
这会创建
config/auth0.php
文件,包含守卫、中间件和路由配置。

3. 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?
  1. Automated - I'll run Auth0 CLI scripts that create the resource and write the exact values to your
    .env
    automatically.
  2. Manual - You create the API yourself in the Auth0 Dashboard (or via
    auth0 apis create
    ) and provide me the Domain and Audience.
Which 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
.env
for you - skip Step 4 below and proceed directly to Step 5.
If 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 \
  --json
Or create manually in Auth0 Dashboard -> Applications -> APIs
你需要在Auth0中创建一个API(不是应用程序)。
暂停 - 继续前请询问用户。
请准确询问以下问题,等待用户回复后再执行其他操作:
"你希望如何创建Auth0 API资源?
  1. 自动创建 - 我会运行Auth0 CLI脚本创建资源,并自动将准确值写入你的
    .env
    文件。
  2. 手动创建 - 你在Auth0控制台自行创建API(或通过
    auth0 apis create
    命令),并提供域名和受众。
你选择哪种方式?(1=自动 / 2=手动)"
在用户回复前,请勿进行任何设置步骤。请勿默认选择手动方式。
如果用户选择自动创建,请遵循设置指南中的完整CLI脚本。自动方式会为你写入
.env
文件 - 跳过下方步骤4,直接进行步骤5。
如果用户选择手动创建,请遵循设置指南(手动设置部分)中的完整说明。然后继续步骤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
.env
:
bash
AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.com
AUTH0_DOMAIN
is your Auth0 tenant domain (without
https://
).
AUTH0_AUDIENCE
is the API identifier you set when creating the API resource in Auth0.
.env
中添加:
bash
AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.com
AUTH0_DOMAIN
是你的Auth0租户域名(不带
https://
前缀)。
AUTH0_AUDIENCE
是你在Auth0创建API资源时设置的API标识符。

5. Configure Auth Guard

5. 配置认证守卫

Update
config/auth.php
to add the API guard:
php
'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:
  • driver
    must be
    auth0.authorizer
    (not
    auth0.authenticator
    which is for web apps)
  • configuration
    must be
    'api'
    which maps to the
    api
    guard in
    config/auth0.php
  • The SDK auto-registers an
    auth0-api
    guard with this config, but defining it explicitly is clearer
更新
config/auth.php
以添加API守卫:
php
'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
    必须为
    auth0.authorizer
    (不是用于Web应用的
    auth0.authenticator
  • configuration
    必须为
    'api'
    ,对应
    config/auth0.php
    中的
    api
    守卫
  • SDK会自动注册带有此配置的
    auth0-api
    守卫,但显式定义更清晰

6. Verify Auth0 Config

6. 验证Auth0配置

After publishing, verify that
config/auth0.php
contains a
guards.api
key with
strategy
set to
SdkConfiguration::STRATEGY_API
(value:
'api'
). This is already present in the published config — no manual editing needed.
The published file uses class constants for keys (e.g.,
Configuration::CONFIG_STRATEGY
), which resolve to the same string values at runtime:
php
'guards' => [
    'api' => [
        'strategy' => SdkConfiguration::STRATEGY_API,  // value: 'api'
    ],
],
The published config also includes
default
and
web
guard sections — these can be ignored for API-only usage. The
STRATEGY_API
strategy disables all session/cookie machinery and enables stateless Bearer token validation.
发布配置后,验证
config/auth0.php
中是否包含
guards.api
键,且
strategy
设置为
SdkConfiguration::STRATEGY_API
(值为
'api'
)。发布的配置文件中已默认包含此设置,无需手动编辑。
发布的文件使用类常量作为键(例如
Configuration::CONFIG_STRATEGY
),运行时会解析为相同的字符串值:
php
'guards' => [
    'api' => [
        'strategy' => SdkConfiguration::STRATEGY_API,  // 值:'api'
    ],
],
发布的配置文件还包含
default
web
守卫部分 - 仅API使用场景下可忽略这些。
STRATEGY_API
策略会禁用所有会话/ cookie机制,启用无状态Bearer令牌验证。

7. Add Protected API Routes

7. 添加受保护的API路由

Laravel 11+ does not include
routes/api.php
by default. If the file does not exist, scaffold it:
bash
php artisan install:api
This creates
routes/api.php
and registers it in
bootstrap/app.php
with the
/api
prefix. It also installs Laravel Sanctum, which is unused but harmless alongside Auth0.
In
routes/api.php
:
php
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
auth:auth0-api
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.
Laravel 11+ 默认不包含
routes/api.php
。如果该文件不存在,生成它:
bash
php artisan install:api
这会创建
routes/api.php
并在
bootstrap/app.php
中注册,前缀为
/api
。同时会安装Laravel Sanctum,它在Auth0旁边是无用但无害的。
routes/api.php
中:
php
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-api
中间件会验证Bearer令牌,通过JWKS端点验证签名,并检查颁发者和受众声明。没有有效令牌的请求会收到401响应。

8. Scope and Permission Checks

8. 权限范围和权限检查

Use the guard's
hasScope()
and
hasPermission()
methods:
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()
    checks the
    scope
    claim (space-separated string in the JWT)
  • hasPermission()
    checks the
    permissions
    claim (array, requires RBAC enabled on the API in Auth0 Dashboard)
使用守卫的
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()
    检查
    scope
    声明(JWT中的空格分隔字符串)
  • hasPermission()
    检查
    permissions
    声明(数组,需要在Auth0控制台的API中启用RBAC)

9. Access Token Claims

9. 访问令牌声明

The authenticated user is a
StatelessUser
instance with dynamic claim access:
php
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:
  • $user->getAuthIdentifier()
    - Returns
    sub
    claim
  • $user->claim_name
    - Dynamic property access via
    __get
  • $user->getAttribute('claim_name')
    - Explicit access
  • $user->jsonSerialize()
    - All claims as array
已认证用户是
StatelessUser
实例,可动态访问声明:
php
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:
bash
php 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
    should return
    {"message":"Public endpoint - no authentication required"}
  • /api/private
    should return HTTP 401
Important: The
-H "Accept: application/json"
header is required. Without it, Laravel's
Authenticate
middleware returns a 302 redirect instead of 401.
If both pass, the guard is working. Kill the background server when done:
bash
kill %1 2>/dev/null
Failcheck: If the server fails to start or responses are unexpected, check that
config/auth0.php
exists and
.env
has
AUTH0_DOMAIN
and
AUTH0_AUDIENCE
set. After 5-6 failed iterations, use
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?
  1. Yes - I'll help you configure an M2M application to get test tokens.
  2. 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.
  1. Create new - I'll create a new M2M application and authorize it for this API.
  2. 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":
bash
auth0 apps create \
  --name "${PWD##*/} (Test App)" \
  --type m2m \
  --no-input --json
Parse JSON with
jq
to extract
client_id
. Do NOT use
--reveal-secrets
. Then create a client grant:
bash
auth0 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
    auth0 test token
    on its own
  • Do NOT ask the user to paste their token
  • Do NOT echo or store the token value
Secure testing (single-command chain):
bash
php 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/null
If the user does NOT ask to test, provide commands for them to run manually:
bash
auth0 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 serve
Test public endpoint (no token needed):
bash
curl -H "Accept: application/json" http://localhost:8000/api/public
Test protected endpoint without token (should return 401):
bash
curl -H "Accept: application/json" http://localhost:8000/api/private
Note: The
Accept: application/json
header is required. Without it, Laravel redirects (302) instead of returning 401.
Test 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开发服务器,验证基础端点在无凭据情况下是否正常工作:
bash
php 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":"公开端点 - 无需认证"}
  • /api/private
    应返回HTTP 401
重要提示: 必须携带
-H "Accept: application/json"
请求头。如果没有,Laravel的
Authenticate
中间件会返回302重定向而非401。
如果两项测试都通过,说明守卫工作正常。完成后关闭后台服务器:
bash
kill %1 2>/dev/null
故障检查: 如果服务器无法启动或响应异常,请检查
config/auth0.php
是否存在,以及
.env
中是否设置了
AUTH0_DOMAIN
AUTH0_AUDIENCE
。经过5-6次失败尝试后,使用
AskUserQuestion
询问用户。
Agent指令:基础测试通过后暂停并询问用户。
当公开端点返回200、私有端点无令牌时返回401的测试通过后,询问用户:
"你的API已设置完成,守卫工作正常(公开端点返回200,无令牌时私有端点返回401)。你需要我帮助你设置使用真实访问令牌的测试吗?
  1. - 我会帮你配置M2M应用以获取测试令牌。
  2. - 我已完成当前操作。
你选择哪种?"
除非用户选择是,否则请勿进行M2M/令牌设置。
Agent指令(仅当用户需要测试时进行M2M应用设置):
如果用户选择设置测试,请询问:
"要测试受保护的端点,你需要一个被授权为此API请求令牌的机器对机器(M2M)应用。
  1. 创建新应用 - 我会创建一个新的M2M应用并授权它访问此API。
  2. 使用现有应用 - 你已有M2M应用,请提供客户端ID,我会授权它访问此API。
你选择哪种?(1=创建新应用 / 2=使用现有应用)"
用户回复前请勿继续。
如果用户选择“创建新应用”:
bash
auth0 apps create \
  --name "${PWD##*/} (Test App)" \
  --type m2m \
  --no-input --json
使用
jq
解析JSON提取
client_id
。请勿使用
--reveal-secrets
。 然后创建客户端授权:
bash
auth0 api post "client-grants" --data '{
  "client_id": "<CLIENT_ID>",
  "audience": "<API_IDENTIFIER>",
  "scope": ["<SCOPES>"]
}'
如果用户选择“使用现有应用”: 请求用户提供客户端ID。创建客户端授权(返回409冲突表示已授权,无需处理)。
Agent指令(令牌隔离 - 关键要求):
Agent绝对不能直接查看或显示访问令牌值。
  • 请勿单独运行
    auth0 test token
  • 请勿要求用户粘贴令牌
  • 请勿回显或存储令牌值
安全测试(单命令链):
bash
php 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
如果用户不要求测试,提供手动运行的命令:
bash
auth0 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
注意:必须携带
Accept: application/json
请求头。如果没有,Laravel会返回302重定向而非401。
使用令牌测试受保护端点:
bash
curl http://localhost:8000/api/private \
  -H "Accept: application/json" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
可通过Auth0控制台 -> API -> 测试标签,或上述M2M流程获取测试令牌。

Common Mistakes

常见错误

MistakeFix
Using
auth0.authenticator
driver for API routes
API guard must use
auth0.authorizer
-
auth0.authenticator
is for session-based web apps
Using
auth:web
middleware for API routes
Use
auth:auth0-api
to specify the API guard
Created an Application instead of an API in Auth0Must create an API resource (Dashboard -> Applications -> APIs)
Passing
domain
with
https://
prefix
Use bare domain:
tenant.us.auth0.com
not
https://tenant.us.auth0.com
Using
auth0/auth0-php
directly
Use
auth0/login
which wraps the SDK with Laravel guards and middleware
Not publishing configRun
php artisan vendor:publish --tag=auth0
before configuring
Missing
AUTH0_AUDIENCE
in
.env
Required for token validation - without it, tokens can't be verified against the correct audience
Using
$request->user()
without guard name
Defaults to the
web
guard - use
auth('auth0-api')->user()
or
$request->user('auth0-api')
Checking
$user->scope
as a string
The
scope
claim in JWTs is space-separated - use
hasScope()
instead of string comparison
Calling
hasPermission()
without enabling RBAC
Must enable "Add Permissions in the Access Token" in Auth0 Dashboard -> APIs -> Settings
Using ID tokens for API authMust use access tokens - ID tokens are for the client app
Setting
configuration => 'web'
on the API guard
Must be
'api'
which maps to the
STRATEGY_API
config in
config/auth0.php
Testing with
curl
without
Accept: application/json
header
Laravel returns 302 redirect instead of 401 - always send
Accept: application/json
for API requests
hasScope()
returns false for scopes not defined on the API
Scopes must be defined on the API resource in Auth0 Dashboard - requesting a scope in the token request does not grant it unless defined
hasPermission()
returns false with M2M tokens
RBAC permissions are only embedded in tokens from user-based flows (Authorization Code), not client-credentials grants
routes/api.php
missing in Laravel 11+
Run
php artisan install:api
to scaffold API routing - Laravel 11 does not include it by default

错误修复方案
API路由使用
auth0.authenticator
驱动
API守卫必须使用
auth0.authorizer
-
auth0.authenticator
用于基于会话的Web应用
API路由使用
auth:web
中间件
使用
auth:auth0-api
指定API守卫
在Auth0中创建了应用程序而非API必须创建API资源(控制台 -> 应用程序 -> API)
domain
参数带有
https://
前缀
使用裸域名:
tenant.us.auth0.com
而非
https://tenant.us.auth0.com
直接使用
auth0/auth0-php
使用
auth0/login
,它将SDK与Laravel守卫和中间件封装在一起
未发布配置文件配置前运行
php artisan vendor:publish --tag=auth0
.env
中缺少
AUTH0_AUDIENCE
令牌验证必需 - 没有它,无法针对正确的受众验证令牌
未指定守卫名称使用
$request->user()
默认使用
web
守卫 - 使用
auth('auth0-api')->user()
$request->user('auth0-api')
$user->scope
作为字符串检查
JWT中的
scope
声明是空格分隔的字符串 - 使用
hasScope()
而非字符串比较
未启用RBAC就调用
hasPermission()
必须在Auth0控制台 -> API -> 设置中启用“在访问令牌中添加权限”
使用ID令牌进行API认证必须使用访问令牌 - ID令牌用于客户端应用
API守卫设置
configuration => 'web'
必须设置为
'api'
,对应
config/auth0.php
中的
STRATEGY_API
配置
使用
curl
测试时未携带
Accept: application/json
请求头
Laravel返回302重定向而非401 - API请求始终携带
Accept: application/json
对未在API上定义的权限范围,
hasScope()
返回false
权限范围必须在Auth0控制台的API资源上定义 - 令牌请求中请求权限范围不会自动授予,除非已定义
M2M令牌下
hasPermission()
返回false
RBAC权限仅嵌入来自用户流(授权码)的令牌,不包含在客户端凭证授予的令牌中
Laravel 11+中缺少
routes/api.php
运行
php artisan install:api
生成API路由 - Laravel 11默认不包含该文件

Key SDK Methods

关键SDK方法

MethodReturnsPurpose
auth('auth0-api')->user()
?StatelessUser
Returns authenticated user or
null
auth('auth0-api')->check()
bool
Whether request has a valid token
auth('auth0-api')->hasScope($scope)
bool
Check if token has a specific scope
auth('auth0-api')->hasPermission($perm)
bool
Check if token has a specific RBAC permission
auth('auth0-api')->id()
?string
Returns the
sub
claim directly
$user->getAuthIdentifier()
int|string|null
Returns
sub
claim
$user->getAttribute('key')
mixed
Returns any claim value
$user->jsonSerialize()
array
Returns all claims as array
auth('auth0-api')->getCredential()
?CredentialEntity
Full credential with decoded token data

方法返回值用途
auth('auth0-api')->user()
?StatelessUser
返回已认证用户或
null
auth('auth0-api')->check()
bool
请求是否带有有效令牌
auth('auth0-api')->hasScope($scope)
bool
检查令牌是否包含特定权限范围
auth('auth0-api')->hasPermission($perm)
bool
检查令牌是否包含特定RBAC权限
auth('auth0-api')->id()
?string
直接返回
sub
声明
$user->getAuthIdentifier()
int|string|null
返回
sub
声明
$user->getAttribute('key')
mixed
返回任意声明值
$user->jsonSerialize()
array
以数组形式返回所有声明
auth('auth0-api')->getCredential()
?CredentialEntity
包含解码令牌数据的完整凭证

Related Skills

相关技能

  • auth0-laravel
    - For Laravel web apps with login/logout using session-based auth
  • auth0-php-api
    - For plain PHP APIs without Laravel
  • auth0-quickstart
    - Initial Auth0 setup
  • auth0-mfa
    - Add Multi-Factor Authentication
  • auth0-cli
    - Manage Auth0 resources from the terminal

  • auth0-laravel
    - 用于带登录/登出的Laravel Web应用,基于会话认证
  • auth0-php-api
    - 用于无Laravel的纯PHP API
  • auth0-quickstart
    - 初始Auth0设置
  • auth0-mfa
    - 添加多因素认证
  • auth0-cli
    - 从终端管理Auth0资源

Quick Reference

快速参考

Guard configuration (
config/auth.php
):
php
'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 access
Environment variables:
  • AUTH0_DOMAIN
    - Auth0 tenant domain (e.g.
    tenant.us.auth0.com
    )
  • AUTH0_AUDIENCE
    - API identifier (e.g.
    https://api.example.com
    )
Common Use Cases:
  • Protect routes ->
    auth:auth0-api
    middleware (see Step 7)
  • Scope enforcement ->
    hasScope()
    (see Step 8)
  • Permission enforcement ->
    hasPermission()
    (see Step 8)
  • Advanced configuration -> API Reference

守卫配置(
config/auth.php
):
php
'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_DOMAIN
    - Auth0租户域名(例如
    tenant.us.auth0.com
  • AUTH0_AUDIENCE
    - API标识符(例如
    https://api.example.com
常见用例:
  • 保护路由 ->
    auth:auth0-api
    中间件(见步骤7)
  • 权限范围强制 ->
    hasScope()
    (见步骤8)
  • 权限强制 ->
    hasPermission()
    (见步骤8)
  • 高级配置 -> 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、配置选项

References

参考链接