Readouble

Laravel 8.x Laravel Fortify

イントロダクションIntroduction

Laravel Fortifyは、Laravelのフロントエンドにとらわれない認証バックエンドの実装です。Fortifyは、ログイン、ユーザー登録、パスワードのリセット、メールの検証など、Laravelの認証機能をすべて実装するために必要なルートとコントローラを登録します。Fortifyをインストールした後に、route:list Artisanコマンドを実行して、Fortifyが登録したルートを確認できます。Laravel Fortify[https://github.com/laravel/fortify] is a frontend agnostic authentication backend implementation for Laravel. Fortify registers the routes and controllers needed to implement all of Laravel's authentication features, including login, registration, password reset, email verification, and more. After installing Fortify, you may run the route:list Artisan command to see the routes that Fortify has registered.

Fortifyは独自のユーザーインターフェイスを提供しません。つまり、登録したルートにリクエストを送信する皆さん自身の​​のユーザーインターフェイスと組み合わせることを目的としています。このドキュメントの残りの部分で、こうしたルートにリクエストを送信する方法について正確に説明します。Since Fortify does not provide its own user interface, it is meant to be paired with your own user interface which makes requests to the routes it registers. We will discuss exactly how to make requests to these routes in the remainder of this documentation.

lightbulb">Tip!! Fortifyは、Laravelの認証機能の実装をすぐに開始できるようにすることを目的としたパッケージであることを忘れないでください。必ずしも使用する必要はありません。 認証パスワードリセットメール確認にあるドキュメントに従って、Laravelの認証サービスをいつでも自分で操作できます。{tip} Remember, Fortify is a package that is meant to give you a head start implementing Laravel's authentication features. You are not required to use it. You are always free to manually interact with Laravel's authentication services by following the documentation available in the authentication[/docs/{{version}}/authentication], password reset[/docs/{{version}}/passwords], and email verification[/docs/{{version}}/verification] documentation.

Fortifyとは?What Is Fortify?

前述のように、Laravel FortifyはLaravelのフロントエンドに依存しない認証バックエンドの実装です。Fortifyは、ログイン、ユーザー登録、パスワードのリセット、メールの検証など、Laravelのすべての認証機能を実装するために必要なルートとコントローラを登録します。As mentioned previously, Laravel Fortify is a frontend agnostic authentication backend implementation for Laravel. Fortify registers the routes and controllers needed to implement all of Laravel's authentication features, including login, registration, password reset, email verification, and more.

Laravelの認証機能を使用するために、Fortifyを使う必要はありません。 認証パスワードリセット、およびメール検証のドキュメントにしたがい、Laravelの認証サービスをいつでも自前で操作できます。You are not required to use Fortify in order to use Laravel's authentication features. You are always free to manually interact with Laravel's authentication services by following the documentation available in the authentication[/docs/{{version}}/authentication], password reset[/docs/{{version}}/passwords], and email verification[/docs/{{version}}/verification] documentation.

Laravelを初めて使用する場合は、Laravel Fortifyを使用する前に、Laravel Breezeアプリケーションスターターキットを調べることをお勧めします。Laravel Breezeは、Tailwind CSSで構築されたユーザーインターフェイスを含む、アプリケーションの認証スカフォールドを提供します。Fortifyとは異なり、Breezeはルートとコントローラをアプリケーションに直接リソース公開します。これにより、Laravel Fortifyによりこれらの機能を実装させる前に、Laravelの認証機能を学習して慣れることができます。If you are new to Laravel, you may wish to explore the Laravel Breeze[/docs/{{version}}/starter-kits] application starter kit before attempting to use Laravel Fortify. Laravel Breeze provides an authentication scaffolding for your application that includes a user interface built with Tailwind CSS[https://tailwindcss.com]. Unlike Fortify, Breeze publishes its routes and controllers directly into your application. This allows you to study and get comfortable with Laravel's authentication features before allowing Laravel Fortify to implement these features for you.

基本的にLaravel Fortifyは、Laravel Breezeのルートとコントローラを持っており、ユーザーインターフェイスを含まないパッケージとして提供しています。これにより特定のフロントエンドに関する意見に縛られることなく、アプリケーションの認証レイヤーのバックエンド実装をすばやくスキャフォールディングできます。Laravel Fortify essentially takes the routes and controllers of Laravel Breeze and offers them as a package that does not include a user interface. This allows you to still quickly scaffold the backend implementation of your application's authentication layer without being tied to any particular frontend opinions.

いつFortifyを使用すべきか?When Should I Use Fortify?

LaravelFortifyをいつ使用するのが適切か疑問に思われるかもしれません。まず、Laravelのアプリケーションスターターキットで説明されているいずれかを使用している場合、Laravelのすべてのアプリケーションスターターキットはあらかじめ完全な認証実装を提供しているため、LaravelFortifyをインストールする必要はありません。 。You may be wondering when it is appropriate to use Laravel Fortify. First, if you are using one of Laravel's application starter kits[/docs/{{version}}/starter-kits], you do not need to install Laravel Fortify since all of Laravel's application starter kits already provide a full authentication implementation.

アプリケーションスターターキットを使用しておらず、アプリケーションに認証機能が必要な場合は、アプリケーションの認証機能を自分で実装するか、Laravel Fortifyを使用してこうした機能のバックエンド実装を提供するか、2つのオプションがあります。If you are not using an application starter kit and your application needs authentication features, you have two options: manually implement your application's authentication features or use Laravel Fortify to provide the backend implementation of these features.

Fortifyのインストールを選択した場合、ユーザーインターフェイスは、ユーザーを認証および登録するために、このドキュメントで詳しく説明されているFortifyの認証ルートにリクエストを送ります。If you choose to install Fortify, your user interface will make requests to Fortify's authentication routes that are detailed in this documentation in order to authenticate and register users.

Fortifyを使用する代わりにLaravelの認証サービスを自前で操作することを選択した場合は、認証パスワードリセットメール検証のドキュメントにしたがってください。If you choose to manually interact with Laravel's authentication services instead of using Fortify, you may do so by following the documentation available in the authentication[/docs/{{version}}/authentication], password reset[/docs/{{version}}/passwords], and email verification[/docs/{{version}}/verification] documentation.

Laravel FortifyとLaravel SanctumLaravel Fortify & Laravel Sanctum

一部の開発者は、Laravel SanctumとLaravel Fortifyの違いについて混乱します。 2つのパッケージは2つの関連はあるが別々の問題を解決するため、Laravel FortifyとLaravel Sanctumは相互に排他的、もしくは競合するパッケージではありません。Some developers become confused regarding the difference between Laravel Sanctum[/docs/{{version}}/sanctum] and Laravel Fortify. Because the two packages solve two different but related problems, Laravel Fortify and Laravel Sanctum are not mutually exclusive or competing packages.

Laravel Sanctumは、APIトークンの管理と、セッションCookieまたはトークンを使用した既存のユーザーの認証のみに関係しています。 Sanctumは、ユーザー登録、パスワードのリセットなどを処理するルートを提供していません。Laravel Sanctum is only concerned with managing API tokens and authenticating existing users using session cookies or tokens. Sanctum does not provide any routes that handle user registration, password reset, etc.

APIを提供するアプリケーション、またはシングルページアプリケーションのバックエンドとして機能するアプリケーションの認証レイヤーを自前で構築しようとしている場合は、Laravel Fortify(ユーザー登録、パスワードのリセットなど)およびLaravel Sanctum(APIトークン管理、セッション認証)の両方を利用すのは完全に可能です。If you are attempting to manually build the authentication layer for an application that offers an API or serves as the backend for a single-page application, it is entirely possible that you will utilize both Laravel Fortify (for user registration, password reset, etc.) and Laravel Sanctum (API token management, session authentication).

インストールInstallation

使用開始するには、Composerパッケージマネージャーを使用してFortifyをインストールします。To get started, install Fortify using the Composer package manager:

composer require laravel/fortify

次に、vendor:publishコマンドを使用してFortifyのリソースを公開します。Next, publish Fortify's resources using the vendor:publish command:

php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"

このコマンドは、Fortifyのアクションをapp/Actionsディレクトリにリソース公開します。ディレクトリが存在しない場合は作成します。さらに、Fortifyの構成ファイルとマイグレーションもリソース公開されます。This command will publish Fortify's actions to your app/Actions directory, which will be created if it does not exist. In addition, Fortify's configuration file and migrations will be published.

次に、データベースをマイグレートする必要があります。Next, you should migrate your database:

php artisan migrate

FortifyサービスプロバイダThe Fortify Service Provider

上で説明したvendor:publishコマンドは、App\Providers\FortifyServiceProviderクラスもリソース公開します。このクラスが、アプリケーションのconfig/app.php構成ファイルのproviders配列内に登録されていることを確認する必要があります。The vendor:publish command discussed above will also publish the App\Providers\FortifyServiceProvider class. You should ensure this class is registered within the providers array of your application's config/app.php configuration file.

Fortifyサービスプロバイダは、Fortifyが公開したアクションを登録し、それぞれのタスクがFortifyによって実行されるときに各アクションを使用するようにFortifyに指示しています。The Fortify service provider registers the actions that Fortify published and instructs Fortify to use them when their respective tasks are executed by Fortify.

Fortifyの機能Fortify Features

fortify設定ファイルには、features設定配列が含まれています。この配列は、Fortifyがデフォルトで公開するバックエンドルート/機能を定義しています。FortifyをLaravel Jetstream和訳)(和文)と組み合わせて使用​​していない場合は、ほとんどのLaravelアプリケーションで提供するであろう基本認証機能である以下の機能のみ有効にすることを推奨します。The fortify configuration file contains a features configuration array. This array defines which backend routes / features Fortify will expose by default. If you are not using Fortify in combination with Laravel Jetstream[https://jetstream.laravel.com], we recommend that you only enable the following features, which are the basic authentication features provided by most Laravel applications:

'features' => [
    Features::registration(),
    Features::resetPasswords(),
    Features::emailVerification(),
],

ビューの無効化Disabling Views

デフォルトでは、Fortifyはログイン画面や登録画面など、ビューを返すことを目的としたルートを定義します。ただし、JavaScript駆動のシングルページアプリケーションを構築している場合は、こうしたルートは必要ない場合があります。そのため、アプリケーションのconfig/fortify.php設定ファイル内のviews設定値をfalseにセットすれば、こうしたルートを完全に無効にできます。By default, Fortify defines routes that are intended to return views, such as a login screen or registration screen. However, if you are building a JavaScript driven single-page application, you may not need these routes. For that reason, you may disable these routes entirely by setting the views configuration value within your application's config/fortify.php configuration file to false:

'views' => false,

ビューの無効化とパスワードリセットDisabling Views & Password Reset

Fortifyのビューを無効にし、アプリケーションでパスワードリセット機能を実装する場合でも、アプリケーションの「パスワードのリセット」ビューの表示を担当するpassword.resetという名前のルートを定義する必要があります。Laravelの Illuminate\Auth\Notifications\ResetPassword通知は、password.resetという名前のルートを介してパスワードリセットURLを生成するため、これが必要です。If you choose to disable Fortify's views and you will be implementing password reset features for your application, you should still define a route named password.reset that is responsible for displaying your application's "reset password" view. This is necessary because Laravel's Illuminate\Auth\Notifications\ResetPassword notification will generate the password reset URL via the password.reset named route.

ユーザー認証Authentication

使い始めるには、「ログイン」ビューを返す方法をFortifyに指示する必要があります。Fortifyはヘッドレス認証ライブラリであることを忘れないでください。あらかじめ完成しているLaravelの認証機能のフロントエンド実装が必要な場合は、アプリケーションスターターキットを使用する必要があります。To get started, we need to instruct Fortify how to return our "login" view. Remember, Fortify is a headless authentication library. If you would like a frontend implementation of Laravel's authentication features that are already completed for you, you should use an application starter kit[/docs/{{version}}/starter-kits].

認証ビューのレンダリングロジックはすべて、Laravel\Fortify\Fortifyクラスで利用できる適切なメソッドを使用してカスタマイズできます。通常、このメソッドはアプリケーションのApp\Providers\FortifyServiceProviderクラスのbootメソッドから呼び出す必要があります。Fortifyはこのビューを返す、/ loginルートの定義を処理します。All of the authentication view's rendering logic may be customized using the appropriate methods available via the Laravel\Fortify\Fortify class. Typically, you should call this method from the boot method of your application's App\Providers\FortifyServiceProvider class. Fortify will take care of defining the /login route that returns this view:

use Laravel\Fortify\Fortify;

/**
 * 全アプリケーションサービスの起動処理
 *
 * @return void
 */
public function boot()
{
    Fortify::loginView(function () {
        return view('auth.login');
    });

    // ...
}

ログインテンプレートには、/loginへのPOSTリクエストを行うフォームが含まれている必要があります。/loginエンドポイントは、文字列のメール/ユーザー名とパスワード(password)を想定しています。 メール/ユーザー名フィールドの名前は、config/fortify.php設定ファイル内のusername値に一致する必要があります。さらに、論理値のrememberフィールドを提供して、Laravelの提供する継続ログイン(rememberme)機能をユーザーが使用することを指定可能にできます。Your login template should include a form that makes a POST request to /login. The /login endpoint expects a string email / username and a password. The name of the email / username field should match the username value within the config/fortify.php configuration file. In addition, a boolean remember field may be provided to indicate that the user would like to use the "remember me" functionality provided by Laravel.

ログイン試行が成功するとFortifyは、アプリケーションのfortify設定ファイル内のhome設定オプションを介して設定したURIへリダイレクトします。ログインリクエストがXHRリクエストの場合、200HTTPレスポンスを返します。If the login attempt is successful, Fortify will redirect you to the URI configured via the home configuration option within your application's fortify configuration file. If the login request was an XHR request, a 200 HTTP response will be returned.

リクエストが成功しなかった場合、ユーザーはログイン画面にリダイレクトされ、バリデーションエラーは共有の$errors Bladeテンプレート変数で共有されます。または、XHRリクエストの場合、バリデーションエラーは422HTTPレスポンスで返されます。If the request was not successful, the user will be redirected back to the login screen and the validation errors will be available to you via the shared $errors Blade template variable[/docs/{{version}}/validation#quick-displaying-the-validation-errors]. Or, in the case of an XHR request, the validation errors will be returned with the 422 HTTP response.

ユーザー認証のカスタマイズCustomizing User Authentication

Fortifyは提供された資格情報とアプリケーション用に構成された認証ガードに基づいて、ユーザーを自動的に取得して認証します。しかし、ログイン資格情報の認証方法とユーザーの取得方法を完全にカスタマイズしたい場合もあります。幸運なことにFortifyでは、Fortify::authenticateUsingメソッドを使用し、これが簡単に実行できます。Fortify will automatically retrieve and authenticate the user based on the provided credentials and the authentication guard that is configured for your application. However, you may sometimes wish to have full customization over how login credentials are authenticated and users are retrieved. Thankfully, Fortify allows you to easily accomplish this using the Fortify::authenticateUsing method.

このメソッドは、受信したHTTPリクエストを受け取るクロージャを引数に取ります。クロージャは、リクエストに添付されたログイン資格情報を検証し、関連するユーザーインスタンスを返す責任があります。資格情報が無効であるかユーザーが見つからない場合、クロージャはnullまたはfalseを返します。通常このメソッドは、FortifyServiceProviderbootメソッドで呼び出す必要があります。This method accepts a closure which receives the incoming HTTP request. The closure is responsible for validating the login credentials attached to the request and returning the associated user instance. If the credentials are invalid or no user can be found, null or false should be returned by the closure. Typically, this method should be called from the boot method of your FortifyServiceProvider:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Laravel\Fortify\Fortify;

/**
 * 全アプリケーションサービスの起動処理
 *
 * @return void
 */
public function boot()
{
    Fortify::authenticateUsing(function (Request $request) {
        $user = User::where('email', $request->email)->first();

        if ($user &&
            Hash::check($request->password, $user->password)) {
            return $user;
        }
    });

    // ...
}

認証ガードAuthentication Guard

アプリケーションのfortify設定ファイル内で、Fortifyが使用する認証ガードをカスタマイズできます。ただし、設定するガードにIlluminate\Contracts\Auth\StatefulGuardを確実に実装してください。Laravel Fortifyを使用してSPAを認証しようとしている場合は、LaravelのデフォルトのwebガードとLaravel Sanctumを組み合わせて使用​​する必要があります。You may customize the authentication guard used by Fortify within your application's fortify configuration file. However, you should ensure that the configured guard is an implementation of Illuminate\Contracts\Auth\StatefulGuard. If you are attempting to use Laravel Fortify to authenticate an SPA, you should use Laravel's default web guard in combination with Laravel Sanctum[https://laravel.com/docs/sanctum].

認証パイプラインのカスタマイズCustomizing The Authentication Pipeline

Laravel Fortifyは、invokableなクラスのパイプラインを通して、ログインリクエストを認証します。必要であれば、ログインリクエストを通すクラスのカスタムパイプラインを定義することができます。各クラスは受信したIlluminate\Http\Requestインスタンスを受け取る__invokeメソッドを持ち、ミドルウェアのように、$next変数を起動して、パイプラインの次のクラスにリクエストを渡す必要があります。Laravel Fortify authenticates login requests through a pipeline of invokable classes. If you would like, you may define a custom pipeline of classes that login requests should be piped through. Each class should have an __invoke method which receives the incoming Illuminate\Http\Request instance and, like middleware[/docs/{{version}}/middleware], a $next variable that is invoked in order to pass the request to the next class in the pipeline.

カスタムパイプラインを定義するには、Fortify::authenticateThroughメソッドを使います。このメソッドはクロージャを引数に取り、ログインリクエストを通すクラスの配列を返す必要があります。典型的に、このメソッドはApp\Providers\FortifyServiceProviderクラスのbootメソッドで呼び出します。To define your custom pipeline, you may use the Fortify::authenticateThrough method. This method accepts a closure which should return the array of classes to pipe the login request through. Typically, this method should be called from the boot method of your App\Providers\FortifyServiceProvider class.

以下で、独自の変更を加える場合の参考として使用できる、デフォルトのパイプライン定義例を紹介します。The example below contains the default pipeline definition that you may use as a starting point when making your own modifications:

use Laravel\Fortify\Actions\AttemptToAuthenticate;
use Laravel\Fortify\Actions\EnsureLoginIsNotThrottled;
use Laravel\Fortify\Actions\PrepareAuthenticatedSession;
use Laravel\Fortify\Actions\RedirectIfTwoFactorAuthenticatable;
use Laravel\Fortify\Fortify;
use Illuminate\Http\Request;

Fortify::authenticateThrough(function (Request $request) {
    return array_filter([
            config('fortify.limiters.login') ? null : EnsureLoginIsNotThrottled::class,
            Features::enabled(Features::twoFactorAuthentication()) ? RedirectIfTwoFactorAuthenticatable::class : null,
            AttemptToAuthenticate::class,
            PrepareAuthenticatedSession::class,
    ]);
});

リダイレクトのカスタマイズCustomizing Redirects

ログインが成功した場合、Fortifyアプリケーションの fortify 設定ファイル内のhome設定オプションで設定されているURIへリダイレクトします。ログインリクエストがXHRリクエストだった場合は、200 HTTPレスポンスを返します。ユーザーがアプリケーションからログアウトした後は、/のURIへリダイレクトします。If the login attempt is successful, Fortify will redirect you to the URI configured via the home configuration option within your application's fortify configuration file. If the login request was an XHR request, a 200 HTTP response will be returned. After a user logs out of the application, the user will be redirected to the / URI.

この動作を高度にカスタマイズする必要がある場合は、LoginResponseLogoutResponse契約の実装をLaravelのサービスコンテナに結合します。通常、これはアプリケーションのApp\Providers\FortifyServiceProviderクラスのregisterメソッド内で行います。If you need advanced customization of this behavior, you may bind implementations of the LoginResponse and LogoutResponse contracts into the Laravel service container[/docs/{{version}}/container]. Typically, this should be done within the register method of your application's App\Providers\FortifyServiceProvider class:

use Laravel\Fortify\Contracts\LogoutResponse;

/**
 * アプリケーションの全サービスの登録
 *
 * @return void
 */
public function register()
{
    $this->app->instance(LogoutResponse::class, new class implements LogoutResponse {
        public function toResponse($request)
        {
            return redirect('/');
        }
    });
}

2要素認証Two Factor Authentication

Fortifyの2要素認証機能を有効にしている場合、ユーザーは認証プロセス中に6桁の数値トークンを入力する必要があります。このトークンは、Google AuthenticatorなどのTOTP互換のモバイル認証アプリケーションから取得できる時間ベースのワンタイムパスワード(TOTP)を使用して生成されます。When Fortify's two factor authentication feature is enabled, the user is required to input a six digit numeric token during the authentication process. This token is generated using a time-based one-time password (TOTP) that can be retrieved from any TOTP compatible mobile authentication application such as Google Authenticator.

使用開始する前に、アプリケーションのApp\Models\Userモデルで、Laravel\Fortify\TwoFactorAuthenticatableトレイトを使用していることを確認してください。Before getting started, you should first ensure that your application's App\Models\User model uses the Laravel\Fortify\TwoFactorAuthenticatable trait:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;

class User extends Authenticatable
{
    use Notifiable, TwoFactorAuthenticatable;
}

次に、ユーザーが2要素認証設定を管理できる画面をアプリケーション内に構築する必要があります。この画面でユーザーが2要素認証を有効または無効にしたり、2要素認証の回復コードを再生成したりできるようにする必要があります。Next, you should build a screen within your application where users can manage their two factor authentication settings. This screen should allow the user to enable and disable two factor authentication, as well as regenerate their two factor authentication recovery codes.

fortify設定ファイルのfeatures配列によりデフォルトで、変更前にパスワードの確認を要求するようにFortifyの2要素認証設定に指示しています。そのため、皆さんのアプリケーションでFortifyの続行時パスワード確認機能を実装する必要があります。By default, the features array of the fortify configuration file instructs Fortify's two factor authentication settings to require password confirmation before modification. Therefore, your application should implement Fortify's password confirmation[#password-confirmation] feature before continuing.

2要素認証の有効化Enabling Two Factor Authentication

2要素認証を有効にするには、アプリケーションはFortifyで定義された/user/two-factor-authenticationエンドポイントにPOSTリクエストを行う必要があります。リクエストが成功すると、ユーザーは前のURLにリダイレクトされ、statusセッション変数はtwo-factor-authentication-enabledにセットされます。テンプレート内でこのstatusセッション変数を検出して、適切な成功メッセージを表示してください。リクエストがXHRリクエストの場合、200 HTTPレスポンスが返されます。To enable two factor authentication, your application should make a POST request to the /user/two-factor-authentication endpoint defined by Fortify. If the request is successful, the user will be redirected back to the previous URL and the status session variable will be set to two-factor-authentication-enabled. You may detect this status session variable within your templates to display the appropriate success message. If the request was an XHR request, 200 HTTP response will be returned:

@if (session('status') == 'two-factor-authentication-enabled')
    <div class="mb-4 font-medium text-sm text-green-600">
        Two factor authentication has been enabled.
    </div>
@endif

次に、ユーザーの認証アプリケーションでスキャンしログインするための、2要素認証QRコードを表示する必要があります。 Bladeを使用してアプリケーションのフロントエンドをレンダリングしている場合は、ユーザーインスタンスで使用可能な twoFactorQrCodeSvgメソッドを使用してQRコードSVGを取得できます。Next, you should display the two factor authentication QR code for the user to scan into their authenticator application. If you are using Blade to render your application's frontend, you may retrieve the QR code SVG using the twoFactorQrCodeSvg method available on the user instance:

$request->user()->twoFactorQrCodeSvg();

JavaScriptを利用したフロントエンドを構築している場合は、/user/two-factor-qr-codeエンドポイントにXHRのGETリクエストを送信して、ユーザーの2要素認証QRコードを取得できます。このエンドポイントは、svgキーを含むJSONオブジェクトを返します。If you are building a JavaScript powered frontend, you may make an XHR GET request to the /user/two-factor-qr-code endpoint to retrieve the user's two factor authentication QR code. This endpoint will return a JSON object containing an svg key.

リカバリコードの表示Displaying The Recovery Codes

また、ユーザーの2要素リカバリコードも表示する必要があります。これらのリカバリコードにより、ユーザーはモバイルデバイスにアクセスできなくなった場合にも認証できます。Bladeを使用してアプリケーションのフロントエンドをレンダリングしている場合は、認証済みのユーザーインスタンスを介してリカバリコードにアクセスできます。You should also display the user's two factor recovery codes. These recovery codes allow the user to authenticate if they lose access to their mobile device. If you are using Blade to render your application's frontend, you may access the recovery codes via the authenticated user instance:

(array) $request->user()->recoveryCodes()

JavaScriptを利用したフロントエンドを構築している場合は、/user/two-factor-recovery-codesエンドポイントに対してXHRのGETリクエストを行ってください。このエンドポイントは、ユーザーのリカバリコードを含むJSON配列を返します。If you are building a JavaScript powered frontend, you may make an XHR GET request to the /user/two-factor-recovery-codes endpoint. This endpoint will return a JSON array containing the user's recovery codes.

ユーザーのリカバリコードを再生成するとき、アプリケーションは/user/two-factor-recovery-codesエンドポイントに対してPOSTリクエストを行う必要があります。To regenerate the user's recovery codes, your application should make a POST request to the /user/two-factor-recovery-codes endpoint.

2要素認証による認証Authenticating With Two Factor Authentication

認証プロセス中にFortifyはユーザーをアプリケーションの2要素認証チャレンジ画面に自動的にリダイレクトします。ただし、アプリケーションがXHRログイン要求を行っている場合、認証の試行が成功した後に返されるJSON応答には、two_factor論理値プロパティを持つJSONオブジェクトが含まれます。この値を調べ、アプリケーションの2要素認証チャレンジ画面にリダイレクトする必要があるかどうかを確認する必要があります。During the authentication process, Fortify will automatically redirect the user to your application's two factor authentication challenge screen. However, if your application is making an XHR login request, the JSON response returned after a successful authentication attempt will contain a JSON object that has a two_factor boolean property. You should inspect this value to know whether you should redirect to your application's two factor authentication challenge screen.

2要素認証機能の実装を開始するには、2要素認証チャレンジビューを返す方法をFortifyに指示する必要があります。 Fortifyの認証ビューレンダリングロジックはすべて、Laravel\Fortify\Fortifyクラスで利用できる適切なメソッドを使用してカスタマイズできます。通常このメソッドは、アプリケーションのApp\Providers\FortifyServiceProviderクラスのbootメソッドから呼び出す必要があります。To begin implementing two factor authentication functionality, we need to instruct Fortify how to return our two factor authentication challenge view. All of Fortify's authentication view rendering logic may be customized using the appropriate methods available via the Laravel\Fortify\Fortify class. Typically, you should call this method from the boot method of your application's App\Providers\FortifyServiceProvider class:

use Laravel\Fortify\Fortify;

/**
 * 全アプリケーションサービスの起動処理
 *
 * @return void
 */
public function boot()
{
    Fortify::twoFactorChallengeView(function () {
        return view('auth.two-factor-challenge');
    });

    // ...
}

Fortifyはこのビューを返す、/two-factor-challengeルートの定義を処理します。two-factor-challengeテンプレートには、/two-factor-challengeエンドポイントにPOSTリクエストを行うフォームを含める必要があります。/two-factor-challengeアクションは、有効なTOTPトークンを含むcodeフィールドまたはユーザーのリカバリコードの1つを含むrecovery_codeフィールドを期待します。Fortify will take care of defining the /two-factor-challenge route that returns this view. Your two-factor-challenge template should include a form that makes a POST request to the /two-factor-challenge endpoint. The /two-factor-challenge action expects a code field that contains a valid TOTP token or a recovery_code field that contains one of the user's recovery codes.

ログインの試行が成功すると、Fortifyはアプリケーションのfortify設定ファイル内のhome設定オプションにより設定されたURIへ、ユーザーをリダイレクトします。ログイン要求がXHR要求であった場合、204 HTTPレスポンスが返されます。If the login attempt is successful, Fortify will redirect the user to the URI configured via the home configuration option within your application's fortify configuration file. If the login request was an XHR request, a 204 HTTP response will be returned.

リクエストが成功しなかった場合、ユーザーは2要素認証画面へリダイレクトされ、バリデーションエラーは共有の$errors Bladeテンプレート変数により利用できます。XHRリクエストの場合、バリデーションエラーは422 HTTPレスポンスで返されます。If the request was not successful, the user will be redirected back to the two factor challenge screen and the validation errors will be available to you via the shared $errors Blade template variable[/docs/{{version}}/validation#quick-displaying-the-validation-errors]. Or, in the case of an XHR request, the validation errors will be returned with a 422 HTTP response.

2要素認証の無効化Disabling Two Factor Authentication

2要素認証を無効にするには、アプリケーションが/user/two-factor-authenticationエンドポイントに対してDELETEリクエストを行う必要があります。 Fortifyの2要素認証エンドポイントは、呼び出される前にパスワード確認を必要とすることを忘れないでください。To disable two factor authentication, your application should make a DELETE request to the /user/two-factor-authentication endpoint. Remember, Fortify's two factor authentication endpoints require password confirmation[#password-confirmation] prior to being called.

ユーザー登録Registration

アプリケーションの登録機能の実装をはじめるには、「登録(register)」ビューを返す方法をFortifyに指示する必要があります。Fortifyはヘッドレス認証ライブラリであることを忘れないでください。あらかじめ完成しているLaravelの認証機能のフロントエンド実装が必要な場合は、アプリケーションスターターキットを使用する必要があります。To begin implementing our application's registration functionality, we need to instruct Fortify how to return our "register" view. Remember, Fortify is a headless authentication library. If you would like a frontend implementation of Laravel's authentication features that are already completed for you, you should use an application starter kit[/docs/{{version}}/starter-kits].

Fortifyのビューレンダリングロジックはすべて、Laravel\Fortify\Fortifyクラスで利用できる適切なメソッドを使用してカスタマイズできます。通常、このメソッドは、App\Providers\FortifyServiceProviderクラスの bootメソッドから呼び出す必要があります。All of the Fortify's view rendering logic may be customized using the appropriate methods available via the Laravel\Fortify\Fortify class. Typically, you should call this method from the boot method of your App\Providers\FortifyServiceProvider class:

use Laravel\Fortify\Fortify;

/**
 * 全アプリケーションサービスの起動処理
 *
 * @return void
 */
public function boot()
{
    Fortify::registerView(function () {
        return view('auth.register');
    });

    // ...
}

Fortifyは、このビューを返す/registerルートの定義を処理します。registerテンプレートには、Fortifyが定義した/registerエンドポイントへPOSTリクエストを行うフォームが含まれている必要があります。Fortify will take care of defining the /register route that returns this view. Your register template should include a form that makes a POST request to the /register endpoint defined by Fortify.

/registerエンドポイントは、文字列のname、文字列のメールアドレス/ユーザー名、passwordpassword_confirmationフィールドを必要とします。メール/ユーザー名フィールドの名前は、アプリケーションのfortify設定ファイル内で定義するusername設定値と一致させる必要があります。The /register endpoint expects a string name, string email address / username, password, and password_confirmation fields. The name of the email / username field should match the username configuration value defined within your application's fortify configuration file.

登録の試行が成功すると、Fortifyはアプリケーションのfortify設定ファイル内のhome設定オプションで指定してあるURIにユーザーをリダイレクトします。ログインリクエストがXHRリクエストの場合、200 HTTPレスポンスが返されます。If the registration attempt is successful, Fortify will redirect the user to the URI configured via the home configuration option within your application's fortify configuration file. If the login request was an XHR request, a 200 HTTP response will be returned.

リクエストが成功しなかった場合、ユーザーは登録画面にリダイレクトされ、バリデーションエラーは共有の$errors Bladeテンプレート変数により利用可能になります。XHRリクエストの場合、バリデーションエラーは422 HTTPレスポンスで返されます。If the request was not successful, the user will be redirected back to the registration screen and the validation errors will be available to you via the shared $errors Blade template variable[/docs/{{version}}/validation#quick-displaying-the-validation-errors]. Or, in the case of an XHR request, the validation errors will be returned with a 422 HTTP response.

ユーザー登録のカスタマイズCustomizing Registration

ユーザーのバリデーションと作成のプロセスは、Laravel Fortifyのインストール時に生成されるApp\Actions\Fortify\CreateNewUserアクションを変更すればカスタマイズできます。The user validation and creation process may be customized by modifying the App\Actions\Fortify\CreateNewUser action that was generated when you installed Laravel Fortify.

パスワードリセットPassword Reset

パスワードリセットリンクのリクエストRequesting A Password Reset Link

アプリケーションのパスワードリセット機能の実装を開始するには、「パスワードを忘れた(forgot password)」ビューを返す方法をFortifyに指示する必要があります。Fortifyはヘッドレス認証ライブラリであることを忘れないでください。あらかじめ完成しているLaravelの認証機能のフロントエンド実装が必要な場合は、アプリケーションスターターキットを使用する必要があります。To begin implementing our application's password reset functionality, we need to instruct Fortify how to return our "forgot password" view. Remember, Fortify is a headless authentication library. If you would like a frontend implementation of Laravel's authentication features that are already completed for you, you should use an application starter kit[/docs/{{version}}/starter-kits].

Fortifyのビューレンダリングロジックはすべて、Laravel\Fortify\Fortifyクラスで利用できる適切なメソッドを使用してカスタマイズできます。通常このメソッドは、アプリケーションのApp\Providers\FortifyServiceProviderクラスのbootメソッドから呼び出す必要があります。All of Fortify's view rendering logic may be customized using the appropriate methods available via the Laravel\Fortify\Fortify class. Typically, you should call this method from the boot method of your application's App\Providers\FortifyServiceProvider class:

use Laravel\Fortify\Fortify;

/**
 * 全アプリケーションサービスの起動処理
 *
 * @return void
 */
public function boot()
{
    Fortify::requestPasswordResetLinkView(function () {
        return view('auth.forgot-password');
    });

    // ...
}

Fortifyは、このビューを返す/forgot-passwordエンドポイントの定義を処理します。forgot-passwordテンプレートには/forgot-passwordエンドポイントにPOSTリクエストを行うフォームを含める必要があります。Fortify will take care of defining the /forgot-password endpoint that returns this view. Your forgot-password template should include a form that makes a POST request to the /forgot-password endpoint.

/forgot-passwordエンドポイントは文字列emailフィールドを必要とします。このフィールド/データベースカラムの名前は、アプリケーションのfortify設定ファイル内のemail設定値と一致する必要があります。The /forgot-password endpoint expects a string email field. The name of this field / database column should match the email configuration value within your application's fortify configuration file.

パスワードリセットのリンクリクエスト処理レスポンスHandling The Password Reset Link Request Response

パスワードリセットリンクリクエストが成功した場合、Fortifyはユーザーを/forgot-passwordエンドポイントにリダイレクトし、パスワードのリセットに使用できる安全なリンクを記載したメールをユーザーに送信します。リクエストがXHRリクエストの場合、200 HTTPレスポンスを返します。If the password reset link request was successful, Fortify will redirect the user back to the /forgot-password endpoint and send an email to the user with a secure link they can use to reset their password. If the request was an XHR request, a 200 HTTP response will be returned.

リクエストが成功した後、/forgot-passwordエンドポイントにリダイレクトされたとき、statusセッション変数を使用して、パスワードリセットリンクリクエストの実行ステータスを表示できます。このセッション変数の値は、アプリケーションのpasswords言語ファイル内で定義されている翻訳文字列の1つと一致します。After being redirected back to the /forgot-password endpoint after a successful request, the status session variable may be used to display the status of the password reset link request attempt. The value of this session variable will match one of the translation strings defined within your application's passwords language file[/docs/{{version}}/localization]:

@if (session('status'))
    <div class="mb-4 font-medium text-sm text-green-600">
        {{ session('status') }}
    </div>
@endif

リクエストが成功しなかった場合、ユーザーはリクエストパスワードリセットリンク画面にリダイレクトされ、共有の$errors Bladeテンプレート変数により、バリデーションエラーを利用できます。XHRリクエストの場合、バリデーションエラーは422 HTTPレスポンスで返されます。If the request was not successful, the user will be redirected back to the request password reset link screen and the validation errors will be available to you via the shared $errors Blade template variable[/docs/{{version}}/validation#quick-displaying-the-validation-errors]. Or, in the case of an XHR request, the validation errors will be returned with a 422 HTTP response.

パスワードのリセットResetting The Password

アプリケーションのパスワードリセット機能の実装を完了するには、「パスワードのリセット(reset password)」ビューを返す方法をFortifyに指示する必要があります。To finish implementing our application's password reset functionality, we need to instruct Fortify how to return our "reset password" view.

Fortifyのビューのレンダリングロジックはすべて、Laravel\Fortify\Fortifyクラスで利用できる適切なメソッドを使用してカスタマイズできます。通常、このメソッドは、アプリケーションのApp\Providers\FortifyServiceProviderクラスのbootメソッドから呼び出す必要があります。All of Fortify's view rendering logic may be customized using the appropriate methods available via the Laravel\Fortify\Fortify class. Typically, you should call this method from the boot method of your application's App\Providers\FortifyServiceProvider class:

use Laravel\Fortify\Fortify;

/**
 * 全アプリケーションサービスの起動処理
 *
 * @return void
 */
public function boot()
{
    Fortify::resetPasswordView(function ($request) {
        return view('auth.reset-password', ['request' => $request]);
    });

    // ...
}

Fortifyは、このビューを表示するためのルートの定義を処理します。reset-passwordテンプレートには、/reset-passwordへのPOSTリクエストを行うフォームを含める必要があります。Fortify will take care of defining the route to display this view. Your reset-password template should include a form that makes a POST request to /reset-password.

/reset-passwordエンドポイントには、文字列のemailフィールド、passwordフィールド、password_confirmationフィールド、request()->route('token')の値を含むtokenという名前の非表示フィールドが必要です。"email"フィールド/データベースカラム名は、アプリケーションのfortify設定ファイル内で定義されているemail設定値と一致する必要があります。The /reset-password endpoint expects a string email field, a password field, a password_confirmation field, and a hidden field named token that contains the value of request()->route('token'). The name of the "email" field / database column should match the email configuration value defined within your application's fortify configuration file.

パスワードリセットの処理レスポンスHandling The Password Reset Response

パスワードリセットのリクエストが成功した場合、Fortifyは新しいパスワードでログインできるように、ユーザーを/loginルートへリダイレクトします。さらに、ログイン画面で正常にリセットした状態を表示できるように、statusセッション変数が設定されます。If the password reset request was successful, Fortify will redirect back to the /login route so that the user can log in with their new password. In addition, a status session variable will be set so that you may display the successful status of the reset on your login screen:

@if (session('status'))
    <div class="mb-4 font-medium text-sm text-green-600">
        {{ session('status') }}
    </div>
@endif

リクエストがXHRリクエストの場合、200 HTTPレスポンスが返されます。If the request was an XHR request, a 200 HTTP response will be returned.

リクエストが成功しなかった場合、ユーザーはパスワードのリセット画面にリダイレクトされ、バリデーションエラーは共有の$errors Bladeテンプレート変数により利用できます。XHRリクエストの場合、バリデーションエラーは422 HTTPレスポンスで返されます。If the request was not successful, the user will be redirected back to the reset password screen and the validation errors will be available to you via the shared $errors Blade template variable[/docs/{{version}}/validation#quick-displaying-the-validation-errors]. Or, in the case of an XHR request, the validation errors will be returned with a 422 HTTP response.

パスワードリセットのカスタマイズCustomizing Password Resets

パスワードのリセットプロセスは、Laravel Fortifyのインストール時に生成されたApp\Actions\ResetUserPasswordアクションを変更することでカスタマイズできます。The password reset process may be customized by modifying the App\Actions\ResetUserPassword action that was generated when you installed Laravel Fortify.

メールの確認Email Verification

ユーザー登録後、ユーザーがアプリケーションへアクセスし続ける前に、ユーザーのメールアドレスを確認したい場合があります。これを行うには、fortify設定ファイルのfeatures配列でemailVerification機能を確実に有効にしてください。次に、App\Models\UserクラスがIlluminate\Contracts\Auth\MustVerifyEmailインターフェイスを実装していることを確認する必要があります。After registration, you may wish for users to verify their email address before they continue accessing your application. To get started, ensure the emailVerification feature is enabled in your fortify configuration file's features array. Next, you should ensure that your App\Models\User class implements the Illuminate\Contracts\Auth\MustVerifyEmail interface.

これらの2つの設定手順が完了すると、新しく登録したユーザーへメールアドレスを所有していることを確認するメールが届きます。ただし、メール内の確認リンクをクリックする必要があることをユーザーに通知する、メール確認画面の表示方法をFortifyに通知する必要があります。Once these two setup steps have been completed, newly registered users will receive an email prompting them to verify their email address ownership. However, we need to inform Fortify how to display the email verification screen which informs the user that they need to go click the verification link in the email.

Fortifyのビューのレンダリングロジックはすべて、Laravel\Fortify\Fortifyクラスで利用できる適切なメソッドを使用してカスタマイズできます。通常、このメソッドは、アプリケーションのApp\Providers\FortifyServiceProviderクラスのbootメソッドから呼び出す必要があります。All of Fortify's view's rendering logic may be customized using the appropriate methods available via the Laravel\Fortify\Fortify class. Typically, you should call this method from the boot method of your application's App\Providers\FortifyServiceProvider class:

use Laravel\Fortify\Fortify;

/**
 * 全アプリケーションサービスの起動処理
 *
 * @return void
 */
public function boot()
{
    Fortify::verifyEmailView(function () {
        return view('auth.verify-email');
    });

    // ...
}

Fortifyは、ユーザーがLaravel組み込み済みのverifiedミドルウェアにより、/email/verifyエンドポイントへリダイレクトされたときにこのビューを表示するルートの定義を処理します。Fortify will take care of defining the route that displays this view when a user is redirected to the /email/verify endpoint by Laravel's built-in verified middleware.

verify-emailテンプレートには、メールアドレスに送信されたメール確認リンクをクリックするようにユーザーへ指示する情報メッセージを含める必要があります。Your verify-email template should include an informational message instructing the user to click the email verification link that was sent to their email address.

メール検証リンクの再送信Resending Email Verification Links

必要に応じて、アプリケーションのverify-emailテンプレートにボタンを追加して、/email/verification-notificationエンドポイントへのPOSTリクエストを送信することもできます。このエンドポイントがリクエストを受信すると、新しい確認メールリンクがユーザーにメールで送信されるため、前の確認リンクが誤って削除されたり失われたりした場合でも、ユーザーは新しい確認リンクを取得できます。If you wish, you may add a button to your application's verify-email template that triggers a POST request to the /email/verification-notification endpoint. When this endpoint receives a request, a new verification email link will be emailed to the user, allowing the user to get a new verification link if the previous one was accidentally deleted or lost.

確認リンクの電子メールを再送信するリクエストが成功した場合、Fortifyはユーザーをstatusセッション変数とともに、/email/verifyエンドポイントにリダイレクトします。この変数でユーザーに操作が成功したメッセージを伝えられます。リクエストがXHRリクエストの場合、202 HTTPレスポンスが返されます。If the request to resend the verification link email was successful, Fortify will redirect the user back to the /email/verify endpoint with a status session variable, allowing you to display an informational message to the user informing them the operation was successful. If the request was an XHR request, a 202 HTTP response will be returned:

@if (session('status') == 'verification-link-sent')
    <div class="mb-4 font-medium text-sm text-green-600">
        A new email verification link has been emailed to you!
    </div>
@endif

ルートの保護Protecting Routes

ルートまたはルートのグループでユーザーが自分のメールアドレスを確認する必要があることを指定するには、Laravelの組み込みのverifiedミドルウェアをルートに指定する必要があります。このミドルウェアは、アプリケーションのApp\Http\Kernelクラスで登録されています。To specify that a route or group of routes requires that the user has verified their email address, you should attach Laravel's built-in verified middleware to the route. This middleware is registered within your application's App\Http\Kernel class:

Route::get('/dashboard', function () {
    // ...
})->middleware(['verified']);

パスワードの確認Password Confirmation

アプリケーションを構築していると、実行する前にユーザーへパスワードを確認してもらう必要のあるアクションが、よく発生する場合があります。通常これらのルートは、Laravelへ組み込み済みのpassword.confirmミドルウェアによって保護されています。While building your application, you may occasionally have actions that should require the user to confirm their password before the action is performed. Typically, these routes are protected by Laravel's built-in password.confirm middleware.

パスワード確認機能の実装を開始するには、アプリケーションの「パスワード確認(password confirmation)」ビューを返す方法をFortifyに指示する必要があります。Fortifyはヘッドレス認証ライブラリであることを忘れないでください。あらかじめ完成しているLaravelの認証機能のフロントエンド実装が必要な場合は、アプリケーションスターターキットを使用する必要があります。To begin implementing password confirmation functionality, we need to instruct Fortify how to return our application's "password confirmation" view. Remember, Fortify is a headless authentication library. If you would like a frontend implementation of Laravel's authentication features that are already completed for you, you should use an application starter kit[/docs/{{version}}/starter-kits].

Fortifyのビューレンダリングロジックはすべて、Laravel\Fortify\Fortifyクラスで利用できる適切なメソッドを使用してカスタマイズできます。通常、このメソッドは、アプリケーションのApp\Providers\FortifyServiceProviderクラスのbootメソッドから呼び出す必要があります。All of Fortify's view rendering logic may be customized using the appropriate methods available via the Laravel\Fortify\Fortify class. Typically, you should call this method from the boot method of your application's App\Providers\FortifyServiceProvider class:

use Laravel\Fortify\Fortify;

/**
 * 全アプリケーションサービスの起動処理
 *
 * @return void
 */
public function boot()
{
    Fortify::confirmPasswordView(function () {
        return view('auth.confirm-password');
    });

    // ...
}

Fortifyは、このビューを返す/user/confirm-passwordエンドポイントの定義を処理します。confirm-passwordテンプレートは、/user/confirm-passwordエンドポイントへPOSTリクエストを行うフォームを含める必要があります。/user/confirm-passwordエンドポイントは、ユーザーの現在のパスワードを含むpasswordフィールドが渡されることを期待しています。Fortify will take care of defining the /user/confirm-password endpoint that returns this view. Your confirm-password template should include a form that makes a POST request to the /user/confirm-password endpoint. The /user/confirm-password endpoint expects a password field that contains the user's current password.

パスワードがユーザーの現在のパスワードと一致する場合、Fortifyはユーザーをアクセスしようとしたルートにリダイレクトします。リクエストがXHRリクエストの場合、201 HTTPレスポンスが返されます。If the password matches the user's current password, Fortify will redirect the user to the route they were attempting to access. If the request was an XHR request, a 201 HTTP response will be returned.

リクエストが成功しなかった場合、ユーザーはパスワードの確認画面にリダイレクトされ、共有の$errorsBladeテンプレート変数を利用してバリデーションエラーが利用できます。XHRリクエストの場合、バリデーションエラーは422 HTTPレスポンスで返されます。If the request was not successful, the user will be redirected back to the confirm password screen and the validation errors will be available to you via the shared $errors Blade template variable. Or, in the case of an XHR request, the validation errors will be returned with a 422 HTTP response.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作