auth0-laravel

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 Laravel Web App Integration

Auth0 Laravel Web应用集成

Add login, logout, and user profile to a Laravel web application using
auth0/login
(Laravel Auth0 SDK).

使用
auth0/login
(Laravel Auth0 SDK)为Laravel Web应用添加登录、登出和用户个人功能。

Prerequisites

前提条件

  • Laravel 11+ application
  • PHP 8.2+ with extensions:
    mbstring
    ,
    openssl
    ,
    json
  • 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
    auth0-quickstart
    skill first
  • Laravel 11+版本的应用
  • PHP 8.2+版本,并安装以下扩展:
    mbstring
    openssl
    json
  • 已安装Composer
  • 已配置Auth0常规Web应用(不能是API,必须是应用类型)
  • 如果您尚未设置Auth0,请先使用
    auth0-quickstart
    技能

When NOT to Use

不适用场景

ScenarioUse Instead
Laravel API with JWT Bearer validation
auth0-laravel-api
(stateless token guard)
Plain PHP (no framework) web app
auth0-php
Plain PHP API
auth0-php-api
Single Page Applications
auth0-react
,
auth0-vue
, or
auth0-angular
Next.js applications
auth0-nextjs
Node.js web apps
auth0-express
or
auth0-fastify
Flask web apps
auth0-flask

场景替代方案
使用JWT Bearer验证的Laravel API
auth0-laravel-api
(无状态令牌Guard)
无框架的纯PHP Web应用
auth0-php
纯PHP API
auth0-php-api
单页应用
auth0-react
auth0-vue
auth0-angular
Next.js应用
auth0-nextjs
Node.js Web应用
auth0-express
auth0-fastify
Flask Web应用
auth0-flask

Quick Start Workflow

快速开始流程

1. Install SDK

1. 安装SDK

bash
composer require auth0/login
The
auth0/login
package requires
auth0/auth0-php
(v8.19+) and will install it automatically. It also requires a PSR-18 HTTP client - if you don't already have one, install Guzzle:
bash
composer require guzzlehttp/guzzle guzzlehttp/psr7
bash
composer require auth0/login
auth0/login
包依赖
auth0/auth0-php
(v8.19+),会自动安装该依赖。它还需要一个PSR-18 HTTP客户端,如果您还没有安装,可以安装Guzzle:
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
文件,包含Guard、中间件和路由配置。

3. Configure Environment

3. 配置环境变量

Add to your
.env
:
bash
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}/callback
AUTH0_DOMAIN
is your Auth0 tenant domain (without
https://
).
AUTH0_CLIENT_ID
and
AUTH0_CLIENT_SECRET
come from your Auth0 Application settings.
AUTH0_AUDIENCE
must be set to an API identifier registered in Auth0 (Auth0 Dashboard > Applications > APIs) - without it, Auth0 returns opaque access tokens that the SDK cannot decode, causing a crash on session restore. The SDK uses
APP_KEY
as the cookie secret by default - no separate secret needed.
Important: Ensure
APP_URL
includes the port if using the built-in dev server (
http://localhost:8000
). Fresh Laravel installs default to
http://localhost
(no port) which causes callback URL mismatches.
添加到您的
.env
文件中:
bash
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}/callback
AUTH0_DOMAIN
是您的Auth0租户域名(不带
https://
前缀)。
AUTH0_CLIENT_ID
AUTH0_CLIENT_SECRET
来自您的Auth0应用设置。
AUTH0_AUDIENCE
必须设置为在Auth0中注册的API标识符(Auth0控制台 > 应用 > APIs)——如果不设置,Auth0会返回无法被SDK解码的不透明访问令牌,导致会话恢复时崩溃。SDK默认使用
APP_KEY
作为Cookie密钥,无需单独设置密钥。
重要提示:如果使用内置开发服务器,请确保
APP_URL
包含端口(如
http://localhost:8000
)。全新安装的Laravel默认使用
http://localhost
(不带端口),这会导致回调URL不匹配。

4. 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
config/auth.php
to use Auth0 guards:
php
'guards' => [
    'web' => [
        'driver' => 'auth0.authenticator',
        'provider' => 'auth0-provider',
        'configuration' => 'web',
    ],
],

'providers' => [
    'auth0-provider' => [
        'driver' => 'auth0.provider',
        'repository' => 'auth0.repository',
    ],
],
The
configuration
key maps to the guard definition in
config/auth0.php
(
web
uses
STRATEGY_REGULAR
with session-based auth). We override the default
web
guard so that Laravel's built-in
auth
middleware and
auth()->user()
work without specifying a guard name. The SDK also auto-registers an
auth0-session
guard with identical config, but overriding
web
is simpler.
更新
config/auth.php
以使用Auth0 Guard:
php
'guards' => [
    'web' => [
        'driver' => 'auth0.authenticator',
        'provider' => 'auth0-provider',
        'configuration' => 'web',
    ],
],

'providers' => [
    'auth0-provider' => [
        'driver' => 'auth0.provider',
        'repository' => 'auth0.repository',
    ],
],
configuration
键对应
config/auth0.php
中的Guard定义(
web
使用
STRATEGY_REGULAR
,即基于会话的认证)。我们覆盖默认的
web
Guard,这样Laravel内置的
auth
中间件和
auth()->user()
无需指定Guard名称即可正常工作。SDK还会自动注册一个
auth0-session
Guard,配置与
web
相同,但覆盖
web
Guard更简单。

6. Routes Are Auto-Registered

6. 路由自动注册

The SDK automatically registers these routes when
registerAuthenticationRoutes
is
true
in
config/auth0.php
:
  • GET /login
    - Redirects to Auth0 Universal Login
  • GET /callback
    - Handles OAuth callback, exchanges code for tokens
  • GET /logout
    - Destroys session and redirects to Auth0 logout
No manual route definitions needed for the auth flow.
config/auth0.php
中的
registerAuthenticationRoutes
设为
true
时,SDK会自动注册以下路由:
  • GET /login
    - 重定向到Auth0通用登录页面
  • GET /callback
    - 处理OAuth回调,交换代码获取令牌
  • GET /logout
    - 销毁会话并重定向到Auth0登出页面
无需手动定义认证流程的路由。

7. Add Protected Routes

7. 添加受保护路由

In
routes/web.php
:
php
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
auth
middleware works with the Auth0 guard. Unauthenticated users are redirected to
/login
.
routes/web.php
中:
php
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()]);
    });
});
标准的
auth
中间件可与Auth0 Guard配合使用。未认证用户会被重定向到
/login

8. Create Views

8. 创建视图

Create
resources/views/home.blade.php
:
blade
<!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.php
:
blade
<!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.php
blade
<!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.php
blade
<!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 serve
Visit
http://localhost:8000
and click Login.
Important: Always access the app via
http://localhost:8000
(not
http://127.0.0.1:8000
). The callback URL uses
localhost
, so the session cookie must be set for
localhost
to persist across the Auth0 login redirect. Using
127.0.0.1
causes an "Invalid state" error because the session cookie won't be sent to the
localhost
callback URL.

bash
php artisan serve
访问
http://localhost:8000
并点击登录。
重要提示:请始终通过
http://localhost:8000
访问应用(不要使用
http://127.0.0.1:8000
)。回调URL使用
localhost
,因此会话Cookie必须针对
localhost
设置,才能在Auth0登录重定向后保持有效。使用
127.0.0.1
会导致“无效状态”错误,因为会话Cookie不会发送到
localhost
回调URL。

Common Mistakes

常见错误

MistakeFix
Using
auth0/auth0-php
directly in Laravel
Use
auth0/login
which wraps the SDK with Laravel guards, middleware, and routes
App created as SPA type in Auth0 DashboardMust be Regular Web Application for server-side session auth
Missing callback URL in Auth0 DashboardAdd
http://localhost:8000/callback
to Allowed Callback URLs
Missing logout URL in Auth0 DashboardAdd
http://localhost:8000
to Allowed Logout URLs
Not publishing the configRun
php artisan vendor:publish --tag=auth0
before configuring
Using wrong guard driver nameDriver is
auth0.authenticator
(not
auth0
or
auth0.guard
)
Forgetting to set
APP_KEY
Run
php artisan key:generate
- the SDK uses this as cookie secret
Calling
Auth0::getCredentials()
directly
Use Laravel's
auth()->user()
- the SDK integrates via guards
Manually defining
/login
,
/callback
,
/logout
routes
Routes are auto-registered by the service provider
Setting
AUTH0_DOMAIN
with
https://
prefix
Use bare domain:
tenant.us.auth0.com
not
https://tenant.us.auth0.com
Using
$request->user()
without middleware
Only available in routes with the
auth
middleware applied
Missing
AUTH0_AUDIENCE
env var
Without an audience, Auth0 returns opaque tokens the SDK cannot parse - causes "JWT string must contain two dots" crash
Visiting
http://127.0.0.1:8000
instead of
http://localhost:8000
Session cookies set for
127.0.0.1
won't be sent to the
localhost
callback - causes "Invalid state" error
Using
$user->getName()
or
$user->getEmail()
StatefulUser
uses magic
__get
- use
$user->name
,
$user->email
,
$user->picture

错误操作修复方案
在Laravel中直接使用
auth0/auth0-php
使用
auth0/login
,它将SDK与Laravel的Guard、中间件和路由进行了封装
在Auth0控制台中创建SPA类型的应用必须使用常规Web应用类型才能支持服务端会话认证
Auth0控制台中未添加回调URL
http://localhost:8000/callback
添加到允许的回调URL列表
Auth0控制台中未添加登出URL
http://localhost:8000
添加到允许的登出URL列表
未发布配置文件在配置前执行
php artisan vendor:publish --tag=auth0
使用错误的Guard驱动名称驱动名称应为
auth0.authenticator
(不是
auth0
auth0.guard
忘记设置
APP_KEY
执行
php artisan key:generate
——SDK使用该密钥作为Cookie加密密钥
直接调用
Auth0::getCredentials()
使用Laravel的
auth()->user()
——SDK通过Guard集成
手动定义
/login
/callback
/logout
路由
路由由服务提供者自动注册
AUTH0_DOMAIN
设置了
https://
前缀
使用纯域名:
tenant.us.auth0.com
而非
https://tenant.us.auth0.com
未使用中间件就调用
$request->user()
仅在应用了
auth
中间件的路由中可用
缺少
AUTH0_AUDIENCE
环境变量
未设置受众时,Auth0会返回无法被SDK解析的不透明令牌——导致“JWT字符串必须包含两个点”错误
访问
http://127.0.0.1:8000
而非
http://localhost:8000
针对
127.0.0.1
设置的会话Cookie不会发送到
localhost
回调URL——导致“无效状态”错误
使用
$user->getName()
$user->getEmail()
StatefulUser
使用魔术方法
__get
——使用
$user->name
$user->email
$user->picture

Key SDK Methods

SDK核心方法

MethodUsagePurpose
auth()->user()
In routes/controllersReturns the authenticated
StatefulUser
or
null
auth()->check()
In routes/controllers/viewsReturns
true
if user is authenticated
auth()->guard('web')
When using multiple guardsGets a specific Auth0 guard instance
$user->name
On user objectUser's display name (via
__get
magic)
$user->email
On user objectUser's email (via
__get
magic)
$user->picture
On user objectUser's avatar URL (via
__get
magic)
$user->getAuthIdentifier()
On user objectReturns the Auth0
sub
claim
$user->getAttribute('claim')
On user objectReturns any claim value explicitly
$user->jsonSerialize()
On user objectReturns all user claims as array

方法使用场景用途
auth()->user()
路由/控制器中返回已认证的
StatefulUser
实例或
null
auth()->check()
路由/控制器/视图中用户已认证时返回
true
auth()->guard('web')
使用多个Guard时获取指定的Auth0 Guard实例
$user->name
用户对象上用户显示名称(通过
__get
魔术方法)
$user->email
用户对象上用户邮箱(通过
__get
魔术方法)
$user->picture
用户对象上用户头像URL(通过
__get
魔术方法)
$user->getAuthIdentifier()
用户对象上返回Auth0的
sub
声明
$user->getAttribute('claim')
用户对象上显式返回任意声明的值
$user->jsonSerialize()
用户对象上返回所有用户声明的数组形式

User Object

用户对象

The authenticated user is a
StatefulUser
instance implementing Laravel's
Authenticatable
contract. It uses
__get
magic for property-style access to claims:
php
$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 array
Access any ID token claim as a property:
$user->nickname
,
$user->updated_at
,
$user->sub
, etc. For explicit access, use
$user->getAttribute('claim_name')
.

已认证用户是
StatefulUser
实例,实现了Laravel的
Authenticatable
契约。它使用
__get
魔术方法以属性方式访问声明:
php
$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

相关技能

  • auth0-laravel-api
    - Protect Laravel API routes with JWT Bearer token validation
  • auth0-php
    - Plain PHP web apps without a framework
  • auth0-quickstart
    - Initial Auth0 setup
  • auth0-mfa
    - Add Multi-Factor Authentication
  • auth0-cli
    - Manage Auth0 resources from the terminal

  • auth0-laravel-api
    - 使用JWT Bearer令牌验证保护Laravel API路由
  • auth0-php
    - 无框架的纯PHP Web应用
  • auth0-quickstart
    - 初始化Auth0设置
  • auth0-mfa
    - 添加多因素认证
  • auth0-cli
    - 通过终端管理Auth0资源

Quick Reference

快速参考

Guard configuration (
config/auth.php
):
php
'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>
@endauth
Environment variables:
  • APP_URL
    - Application URL with port (e.g.
    http://localhost:8000
    )
  • AUTH0_DOMAIN
    - Auth0 tenant domain (e.g.
    tenant.us.auth0.com
    )
  • AUTH0_CLIENT_ID
    - Application client ID
  • AUTH0_CLIENT_SECRET
    - Application client secret
  • AUTH0_AUDIENCE
    - API identifier (required for JWT access tokens)
  • AUTH0_REDIRECT_URI
    - Callback URL (defaults to
    ${APP_URL}/callback
    )
  • APP_KEY
    - Laravel app key, used as cookie encryption secret

Guard配置(
config/auth.php
):
php
'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
环境变量:
  • APP_URL
    - 应用URL(包含端口,例如
    http://localhost:8000
  • AUTH0_DOMAIN
    - Auth0租户域名(例如
    tenant.us.auth0.com
  • AUTH0_CLIENT_ID
    - 应用客户端ID
  • AUTH0_CLIENT_SECRET
    - 应用客户端密钥
  • AUTH0_AUDIENCE
    - API标识符(获取JWT访问令牌必需)
  • AUTH0_REDIRECT_URI
    - 回调URL(默认值为
    ${APP_URL}/callback
  • APP_KEY
    - Laravel应用密钥,用作Cookie加密密钥

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、配置选项、用户模型方法

References

参考链接