🔐auth0-laravel
- プラグイン
- auth0
- ライセンス
- Apache-2.0
- ソース
- GitHub で見る ↗
説明
次のような場合に使用: セッションベースのログイン、ログアウト、またはユーザープロフィール機能をLaravelウェブアプリケーションに追加する場合。 `auth0/login`(laravel-auth0)をガードベースの認証と統合します — ユーザーが「Laravelアプリにログインを追加したい」と言った場合にも使用してください。
原文を表示
Use when adding session-based login, logout, or user profile to a Laravel web application. Integrates auth0/login (laravel-auth0) with guard-based auth — use even if the user says "add login to my Laravel app".
ユースケース
- ✓Laravelアプリにログイン機能を追加する
- ✓セッションベースの認証を実装する
- ✓ユーザープロフィール機能を追加する
- ✓Auth0とLaravelを統合する
本文(日本語訳)
Auth0 Laravel Webアプリ統合
auth0/login(Laravel Auth0 SDK)を使用して、LaravelウェブアプリケーションにログインI、ログアウト、ユーザープロフィール機能を追加します。
前提条件
- Laravel 11以降のアプリケーション
- PHP 8.2以降(拡張モジュール:
mbstring、openssl、json) - Composerのインストール済み
- Auth0 Regular Web Applicationの設定済み(APIではなくApplicationであること)
- Auth0をまだ設定していない場合は、先に
auth0-quickstartskillを使用してください
使用しない場合
| シナリオ | 代わりに使用するもの |
|---|---|
| JWT Bearerトークン検証を使用するLaravel API | auth0-laravel-api(ステートレストークンガード) |
| プレーンPHP(フレームワークなし)のWebアプリ | auth0-php |
| プレーンPHPのAPI | auth0-php-api |
| シングルページアプリケーション(SPA) | auth0-react、auth0-vue、または auth0-angular |
| Next.jsアプリケーション | auth0-nextjs |
| Node.js Webアプリ | auth0-express または auth0-fastify |
| Flask Webアプリ | auth0-flask |
クイックスタート手順
1. SDKのインストール
composer require auth0/login
auth0/login パッケージは auth0/auth0-php(v8.19以降)を必要とし、自動的にインストールされます。
また、PSR-18 HTTPクライアントも必要です。既にインストール済みでない場合は、Guzzleをインストールしてください:
composer require guzzlehttp/guzzle guzzlehttp/psr7
2. 設定ファイルの公開
php artisan vendor:publish --tag=auth0
これにより、ガード、ミドルウェア、ルート設定を含む config/auth0.php が生成されます。
3. 環境変数の設定
.env に以下を追加してください:
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ダッシュボード > Applications > APIs)。
これを設定しない場合、Auth0が不透明なアクセストークンを返し、SDKがデコードできずセッション復元時にクラッシュします。
SDKはデフォルトで APP_KEY をCookieのシークレットとして使用するため、別途シークレットを設定する必要はありません。
重要: 組み込みの開発サーバーを使用している場合(http://localhost:8000)、APP_URL にポート番号が含まれていることを確認してください。
Laravelの新規インストール時のデフォルトは http://localhost(ポートなし)であり、コールバックURLの不一致が発生します。
4. Auth0ダッシュボードの設定
Auth0アプリケーション設定にて:
- Application Type: Regular Web Application
- Allowed Callback URLs:
http://localhost:8000/callback - Allowed Logout URLs:
http://localhost:8000
5. 認証ガードの設定
config/auth.php を更新して、Auth0ガードを使用するように設定します:
'guards' => [
'web' => [
'driver' => 'auth0.authenticator',
'provider' => 'auth0-provider',
'configuration' => 'web',
],
],
'providers' => [
'auth0-provider' => [
'driver' => 'auth0.provider',
'repository' => 'auth0.repository',
],
],
configuration キーは config/auth0.php 内のガード定義に対応しています(web はセッションベース認証の STRATEGY_REGULAR を使用)。
デフォルトの web ガードをオーバーライドすることで、Laravelの組み込み auth ミドルウェアや auth()->user() がガード名を指定せずに動作します。
SDKは同一設定の auth0-session ガードも自動登録しますが、web をオーバーライドする方がシンプルです。
6. ルートの自動登録
config/auth0.php で registerAuthenticationRoutes が true の場合、SDKは以下のルートを自動的に登録します:
GET /login- Auth0 Universal LoginへリダイレクトGET /callback- OAuthコールバックを処理し、コードをトークンに交換GET /logout- セッションを破棄し、Auth0のログアウトエンドポイントへリダイレクト
認証フロー用のルートを手動で定義する必要はありません。
7. 保護されたルートの追加
routes/web.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ガードと連携して動作します。
未認証のユーザーは /login にリダイレクトされます。
8. ビューの作成
resources/views/home.blade.php を作成します:
<!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 を作成します:
<!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. 認証のテスト
php artisan serve
http://localhost:8000 にアクセスし、Loginをクリックします。
重要: アプリには必ず http://localhost:8000(http://127.0.0.1:8000 ではなく)でアクセスしてください。
コールバックURLは localhost を使用するため、Auth0ログインリダイレクトをまたいでセッションを維持するには、セッションCookieが localhost に対して設定されている必要があります。
127.0.0.1 を使用すると、セッションCookieが localhost のコールバックURLに送信されず、「Invalid state」エラーが発生します。
よくある間違い
| 間違い | 対処法 |
|---|---|
Laravelで auth0/auth0-php を直接使用している |
Laravelのガード、ミドルウェア、ルートをラップした auth0/login を使用してください |
| Auth0ダッシュボードでSPAタイプのアプリを作成している | サーバーサイドのセッション認証にはRegular Web Applicationを使用してください |
| Auth0ダッシュボードにコールバックURLが未登録 | Allowed Callback URLsに http://localhost:8000/callback を追加してください |
| Auth0ダッシュボードにログアウトURLが未登録 | Allowed Logout URLsに http://localhost:8000 を追加してください |
| 設定ファイルを公開していない | 設定前に php artisan vendor:publish --tag=auth0 を実行してください |
| ガードドライバー名が誤っている | ドライバーは auth0.authenticator です(auth0 や auth0.guard ではありません) |
APP_KEY の設定を忘れている |
php artisan key:generate を実行してください。SDKはこれをCookieシークレットとして使用します |
Auth0::getCredentials() を直接呼び出している |
SDKはガード経由で統合されているため、Laravelの auth()->user() を使用してください |
/login、/callback、/logout ルートを手動定義している |
これらのルートはサービスプロバイダーによって自動登録されます |
AUTH0_DOMAIN に https:// プレフィックスを付けている |
ドメインのみを指定してください: https://tenant.us.auth0.com ではなく tenant.us.auth0.com |
ミドルウェアなしで $request->user() を使用している |
auth ミドルウェアが適用されたルート内でのみ使用可能です |
AUTH0_AUDIENCE 環境変数が未設定 |
audienceがない場合、Auth0は不透明なトークンを返してSDKがパースできず、「JWT string must contain two dots」クラッシュが発生します |
http://localhost:8000 の代わりに http://127.0.0.1:8000 にアクセスしている |
127.0.0.1 に設定されたセッションCookieは localhost コールバックに送信されず、「Invalid state」エラーが発生します |
$user->getName() や $user->getEmail() を使用している |
StatefulUser は __get マジックメソッドを使用するため、$user->name、$user->email、$user->picture を使用してください |
SDKの主なメソッド
| メソッド | 使用箇所 | 目的 |
|---|---|---|
auth()->user() |
ルート/コントローラー内 | 認証済みの StatefulUser、または null を返す |
auth()->check() |
ルート/コントローラー/ビュー内 | ユーザーが認証済みの場合に true を返す |
auth()->guard('web') |
複数のガードを使用する場合 | 特定のAuth0ガードインスタンスを取得する |
$user->name |
ユーザーオブジェクト | ユーザーの表示名(__get マジック経由) |
$user->email |
ユーザーオブジェクト | ユーザーのメールアドレス(__get マジック経由) |
$user->picture |
ユーザーオブジェクト | ユーザーのアバターURL(__get マジック経由) |
$user->getAuthIdentifier() |
ユーザーオブジェクト | Auth0の sub クレームを返す |
$user->getAttribute('claim') |
ユーザーオブジェクト | 任意のクレーム値を明示的に取得する |
$user->jsonSerialize() |
ユーザーオブジェクト | 全ユーザークレームを配列として返す |
ユーザーオブジェクト
認証済みユーザーはLaravelの Authenticatable コントラクトを実装した StatefulUser インスタンスです。
クレームへのプロパティ形式のアクセスには __get マジックメソッドを使用します:
$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') を使用してください。
関連するSkill
auth0-laravel-api- JWT Bearerトークン検証によるLaravel APIルートの保護auth0-php- フレームワークなしのプレーンPHP Webアプリauth0-quickstart- Auth0の初期セットアップauth0-mfa- 多要素認証(MFA)の追加auth0-cli-
原文(English)を表示
Auth0 Laravel Web App Integration
Add login, logout, and user profile to a Laravel web application using auth0/login (Laravel Auth0 SDK).
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-quickstartskill first
When NOT to Use
| Scenario | Use 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 |
Quick Start Workflow
1. Install SDK
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:
composer require guzzlehttp/guzzle guzzlehttp/psr7
2. Publish Configuration
php artisan vendor:publish --tag=auth0
This creates config/auth0.php with guard, middleware, and route configuration.
3. Configure Environment
Add to your .env:
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.
4. Configure Auth0 Dashboard
In your Auth0 Application settings:
- Application Type: Regular Web Application
- Allowed Callback URLs:
http://localhost:8000/callback - Allowed Logout URLs:
http://localhost:8000
5. Configure Auth Guards
Update config/auth.php to use Auth0 guards:
'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.
6. Routes Are Auto-Registered
The SDK automatically registers these routes when registerAuthenticationRoutes is true in config/auth0.php:
GET /login- Redirects to Auth0 Universal LoginGET /callback- Handles OAuth callback, exchanges code for tokensGET /logout- Destroys session and redirects to Auth0 logout
No manual route definitions needed for the auth flow.
7. Add Protected Routes
In routes/web.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.
8. Create Views
Create resources/views/home.blade.php:
<!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:
<!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
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.
Common Mistakes
| Mistake | Fix |
|---|---|
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 Dashboard | Must be Regular Web Application for server-side session auth |
| Missing callback URL in Auth0 Dashboard | Add http://localhost:8000/callback to Allowed Callback URLs |
| Missing logout URL in Auth0 Dashboard | Add http://localhost:8000 to Allowed Logout URLs |
| Not publishing the config | Run php artisan vendor:publish --tag=auth0 before configuring |
| Using wrong guard driver name | Driver 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 |
Key SDK Methods
| Method | Usage | Purpose |
|---|---|---|
auth()->user() |
In routes/controllers | Returns the authenticated StatefulUser or null |
auth()->check() |
In routes/controllers/views | Returns true if user is authenticated |
auth()->guard('web') |
When using multiple guards | Gets a specific Auth0 guard instance |
$user->name |
On user object | User's display name (via __get magic) |
$user->email |
On user object | User's email (via __get magic) |
$user->picture |
On user object | User's avatar URL (via __get magic) |
$user->getAuthIdentifier() |
On user object | Returns the Auth0 sub claim |
$user->getAttribute('claim') |
On user object | Returns any claim value explicitly |
$user->jsonSerialize() |
On user object | Returns all user claims as array |
User Object
The authenticated user is a StatefulUser instance implementing Laravel's Authenticatable contract. It uses __get magic for property-style access to claims:
$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').
Related Skills
auth0-laravel-api- Protect Laravel API routes with JWT Bearer token validationauth0-php- Plain PHP web apps without a frameworkauth0-quickstart- Initial Auth0 setupauth0-mfa- Add Multi-Factor Authenticationauth0-cli- Manage Auth0 resources from the terminal
Quick Reference
Guard configuration (config/auth.php):
'guards' => [
'web' => [
'driver' => 'auth0.authenticator',
'provider' => 'auth0-provider',
'configuration' => 'web',
],
],
'providers' => [
'auth0-provider' => [
'driver' => 'auth0.provider',
'repository' => 'auth0.repository',
],
],
Route protection:
Route::middleware('auth')->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
});
Check auth in 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 IDAUTH0_CLIENT_SECRET- Application client secretAUTH0_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
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
References
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。