Readouble

Laravel 8.x 認証

イントロダクションIntroduction

多くのWebアプリケーションは、ユーザーがアプリケーションで認証して「ログイン」する手段を提供しています。この機能をWebアプリケーションに実装することは、複雑でリスクを伴う可能性のある作業になりえます。このためLaravelは、認証を迅速、安全、かつ簡単に実装するために必要なツールを提供するよう努めています。Many web applications provide a way for their users to authenticate with the application and "login". Implementing this feature in web applications can be a complex and potentially risky endeavor. For this reason, Laravel strives to give you the tools you need to implement authentication quickly, securely, and easily.

Laravelの認証機能は、基本的に「ガード」と「プロバイダ」で構成されています。ガードは、リクエストごとにユーザーを認証する方法を定義します。たとえば、Laravelには、セッションストレージとクッキーを使用して状態を維持する「セッション」ガードを用意しています。At its core, Laravel's authentication facilities are made up of "guards" and "providers". Guards define how users are authenticated for each request. For example, Laravel ships with a session guard which maintains state using session storage and cookies.

プロバイダは、永続ストレージからユーザーを取得する方法を定義します。LaravelはEloquentとデータベースクエリビルダを使用してユーザーを取得するためのサポートを用意しています。ただし、アプリケーションの必要性に応じて、追加のプロバイダを自由に定義できます。Providers define how users are retrieved from your persistent storage. Laravel ships with support for retrieving users using Eloquent[/docs/{{version}}/eloquent] and the database query builder. However, you are free to define additional providers as needed for your application.

アプリケーションの認証設定ファイルはconfig/auth.phpにあります。このファイルは、Laravelの認証サービスの動作を微調整できるように、十分なコメントの付いたオプションがいくつか含まれています。Your application's authentication configuration file is located at config/auth.php. This file contains several well-documented options for tweaking the behavior of Laravel's authentication services.

lightbulb">Tip!! ガードとプロバイダを「役割」や「許可」と混同しないでください。権限を介したユーザーアクションの認可の詳細については、認可のドキュメントを参照してください。{tip} Guards and providers should not be confused with "roles" and "permissions". To learn more about authorizing user actions via permissions, please refer to the authorization[/docs/{{version}}/authorization] documentation.

スターターキットStarter Kits

さっそく始めたいですか?新しいLaravelアプリケーションにLaravelアプリケーションスターターキットをインストールしてください。データベースをマイグレーションした後に、ブラウザで/registerやアプリケーションに割り当てた他のURLへアクセスしてください。スターターキットは、認証システム全体のスカフォールドの面倒を見ます。Want to get started fast? Install a Laravel application starter kit[/docs/{{version}}/starter-kits] in a fresh Laravel application. After migrating your database, navigate your browser to /register or any other URL that is assigned to your application. The starter kits will take care of scaffolding your entire authentication system!

**最終的にLaravelアプリケーションでスターターキットを使用しないことを選択した場合でも、Laravel Breezeスターターキットをインストールすることは、Laravelのすべての認証機能を実際のLaravelプロジェクトに実装する方法を学ぶ素晴らしい機会になるでしょう。**Laravel Breezeは認証コントローラ、ルート、ビューを作成するため、これらのファイル内のコードを調べて、Laravelの認証機能を実装する方法を学べます。Even if you choose not to use a starter kit in your final Laravel application, installing the Laravel Breeze[/docs/{{version}}/starter-kits#laravel-breeze] starter kit can be a wonderful opportunity to learn how to implement all of Laravel's authentication functionality in an actual Laravel project. Since Laravel Breeze creates authentication controllers, routes, and views for you, you can examine the code within these files to learn how Laravel's authentication features may be implemented.

データベースの検討Database Considerations

デフォルトでLaravelはapp/Modelsディレクトリに、App\Models\User Eloquentモデルを用意します。このモデルは、デフォルトのEloquent認証ドライバーで使用します。アプリケーションがEloquentを使用していない場合は、Laravelクエリビルダを使用するdatabase認証プロバイダを使用できます。By default, Laravel includes an App\Models\User Eloquent model[/docs/{{version}}/eloquent] in your app/Models directory. This model may be used with the default Eloquent authentication driver. If your application is not using Eloquent, you may use the database authentication provider which uses the Laravel query builder.

App\Models\Userモデルのデータベーススキーマを構築するときは、パスワード列の長さを確実に60文字以上にしてください。もちろん、新しいLaravelアプリケーションに含まれているusersテーブルのマイグレーションでは、あらかじめこの長さを超えるカラムが作成されます。When building the database schema for the App\Models\User model, make sure the password column is at least 60 characters in length. Of course, the users table migration that is included in new Laravel applications already creates a column that exceeds this length.

さらに、users(または同等の)テーブルに、100文字のnullableな文字列remember_tokenカラムを確実に含めてください。このカラムは、アプリケーションへログインするときに「持続ログイン(remember me)」オプションを選択したユーザーのトークンを格納するために使用します。繰り返しますが、新しいLaravelアプリケーションに含まれているデフォルトのusersテーブルのマイグレーションには、すでにこのカラムが含まれています。Also, you should verify that your users (or equivalent) table contains a nullable, string remember_token column of 100 characters. This column will be used to store a token for users that select the "remember me" option when logging into your application. Again, the default users table migration that is included in new Laravel applications already contains this column.

エコシステム概要Ecosystem Overview

Laravelは認証に関連する複数のパッケージを提供しています。先へ進む前に、Laravelの一般的な認証エコシステムを確認し、各パッケージの意図と目的について説明します。Laravel offers several packages related to authentication. Before continuing, we'll review the general authentication ecosystem in Laravel and discuss each package's intended purpose.

まず、認証がどのように機能するかを確認しましょう。Webブラウザを使用する場合、ユーザーはログインフォームを介してユーザー名とパスワードを入力します。これらのログイン情報が正しい場合、アプリケーションは認証したユーザーに関する情報をユーザーのセッションに保存します。ブラウザに発行されたクッキーにはセッションIDが含まれているため、アプリケーションへの後続のリクエストでユーザーを正しいセッションに関連付けることができます。セッションクッキーを受信すると、アプリケーションはセッションIDに基づいてセッションデータを取得し、認証情報がセッションに保存されていることに注意して、ユーザーを「認証済み」と見なします。First, consider how authentication works. When using a web browser, a user will provide their username and password via a login form. If these credentials are correct, the application will store information about the authenticated user in the user's session[/docs/{{version}}/session]. A cookie issued to the browser contains the session ID so that subsequent requests to the application can associate the user with the correct session. After the session cookie is received, the application will retrieve the session data based on the session ID, note that the authentication information has been stored in the session, and will consider the user as "authenticated".

リモートサービスがAPIへアクセスするために認証する必要がある場合はWebブラウザがないため、通常クッキーは認証に使用されません。代わりにリモートサービスはリクエストごとにAPIトークンをAPIに送信します。アプリケーションは有効なAPIトークンのテーブルに対して受信したトークンを検証し、そのAPIトークンに関連付けられたユーザーによって実行されたものとしてそのリクエストを「認証」します。When a remote service needs to authenticate to access an API, cookies are not typically used for authentication because there is no web browser. Instead, the remote service sends an API token to the API on each request. The application may validate the incoming token against a table of valid API tokens and "authenticate" the request as being performed by the user associated with that API token.

Laravelの組み込みブラウザ認証サービスLaravel's Built-in Browser Authentication Services

Laravelは、通常AuthもしくはSessionファサードを介してアクセスされる組み込みの認証およびセッションサービスを持っています。これらの機能は、Webブラウザから開始された要求に対してクッキーベースの認証を提供します。これらは、ユーザーのログイン情報を確認し、ユーザーを認証できるようにするメソッドを提供しています。さらに、これらのサービスは適切な認証データをユーザーのセッションへ自動的に保存し、ユーザーのセッションクッキーを発行します。これらのサービスの使用方法に関する説明は、このドキュメントに含まれています。Laravel includes built-in authentication and session services which are typically accessed via the Auth and Session facades. These features provide cookie-based authentication for requests that are initiated from web browsers. They provide methods that allow you to verify a user's credentials and authenticate the user. In addition, these services will automatically store the proper authentication data in the user's session and issue the user's session cookie. A discussion of how to use these services is contained within this documentation.

アプリケーションスターターキットApplication Starter Kits

このドキュメントで説明しているように、これらの認証サービスを手動で操作して、アプリケーション独自の認証レイヤーを構築できます。ただし、より素早く開始できるように、認証レイヤー全体の堅牢で最新のスカフォールドを提供する無料パッケージをリリースしました。こうしたパッケージは、Laravel BreezeLaravel JetstreamLaravel Fortifyです。As discussed in this documentation, you can interact with these authentication services manually to build your application's own authentication layer. However, to help you get started more quickly, we have released free packages[/docs/{{version}}/starter-kits] that provide robust, modern scaffolding of the entire authentication layer. These packages are Laravel Breeze[/docs/{{version}}/starter-kits#laravel-breeze], Laravel Jetstream[/docs/{{version}}/starter-kits#laravel-jetstream], and Laravel Fortify[/docs/{{version}}/fortify].

Laravel Breezeは、ログイン、登録、パスワードのリセット、電子メールの確認、パスワードの確認など、Laravelの全認証機能のシンプルで最小限の実装です。Laravel Breezeのビューレイヤーは、Tailwind CSSによりスタイル設定したシンプルなBladeテンプレートで構成しています。使い始めるには、Laravelのアプリケーションスターターキットのドキュメントを確認してください。Laravel Breeze is a simple, minimal implementation of all of Laravel's authentication features, including login, registration, password reset, email verification, and password confirmation. Laravel Breeze's view layer is comprised of simple Blade templates[/docs/{{version}}/blade] styled with Tailwind CSS[https://tailwindcss.com]. To get started, check out the documentation on Laravel's application starter kits[/docs/{{version}}/starter-kits].

Laravel Fortifyは、Laravelのヘッドレス認証バックエンドであり、クッキーベースの認証や2要素認証、メールアドレス確認や他の機能など、このドキュメントにある多くの機能を実装しています。FortifyはLaravel Jetstreamの認証バックエンドを提供していますし、Laravelで認証する必要があるSPAの認証を提供するために、Laravel Sanctumと組み合わせて独立して使用できます。Laravel Fortify is a headless authentication backend for Laravel that implements many of the features found in this documentation, including cookie-based authentication as well as other features such as two-factor authentication and email verification. Fortify provides the authentication backend for Laravel Jetstream or may be used independently in combination with Laravel Sanctum[/docs/{{version}}/sanctum] to provide authentication for an SPA that needs to authenticate with Laravel.

*Laravel Jetstream和訳)(和文)*は、Laravel Fortifyの認証サービスを利用および公開し、美しくモダンなUIにTailwind CSSを使用しているLivewireInertia.jsを使っている、堅牢なアプリケーションのスターターキットです。Laravel Jetstreamにはオプションサポートとして、2要素認証、チームサポート、ブラウザセッション管理、プロファイル管理、およびAPIトークン認証を提供するLaravel Sanctumとの組み込み統合が含まれています。LaravelのAPI認証手法について以降で説明します。Laravel Jetstream[https://jetstream.laravel.com] is a robust application starter kit that consumes and exposes Laravel Fortify's authentication services with a beautiful, modern UI powered by Tailwind CSS[https://tailwindcss.com], Livewire[https://laravel-livewire.com], and / or Inertia.js[https://inertiajs.com]. Laravel Jetstream includes optional support for two-factor authentication, team support, browser session management, profile management, and built-in integration with Laravel Sanctum[/docs/{{version}}/sanctum] to offer API token authentication. Laravel's API authentication offerings are discussed below.

Laravel API認証サービスLaravel's API Authentication Services

Laravelは、APIトークンの管理とリクエストのAPIトークンによる認証を支援する2つのオプションパッケージ、PassportSanctumを提供しています。これらのライブラリとLaravelの組み込みのクッキーベースの認証ライブラリは、相互に排他的ではないことに注意してください。これらのライブラリは主にAPIトークン認証に重点を置いていますが、組み込みの認証サービスはクッキーベースのブラウザ認証に重点を置いています。多くのアプリケーションは、Laravelの組み込みクッキーベースの認証サービスとLaravelのAPI認証パッケージの両方を使用します。Laravel provides two optional packages to assist you in managing API tokens and authenticating requests made with API tokens: Passport[/docs/{{version}}/passport] and Sanctum[/docs/{{version}}/sanctum]. Please note that these libraries and Laravel's built-in cookie based authentication libraries are not mutually exclusive. These libraries primarily focus on API token authentication while the built-in authentication services focus on cookie based browser authentication. Many applications will use both Laravel's built-in cookie based authentication services and one of Laravel's API authentication packages.

PassportPassport

PassportはOAuth2認証プロバイダであり、さまざまなタイプのトークンを発行できる多くのOAuth2「許可タイプ」を提供します。一般にAPI認証は、堅牢で複雑なパッケージです。しかし、ほとんどのアプリケーションは、OAuth2仕様によって提供される複雑な機能を必要としないため、ユーザーと開発者の両者を混乱させる可能性があります。さらに、開発者は、PassportなどのOAuth2認証プロバイダを使用してSPAアプリケーションまたはモバイルアプリケーションを認証する方法で、長い間混乱してきました。Passport is an OAuth2 authentication provider, offering a variety of OAuth2 "grant types" which allow you to issue various types of tokens. In general, this is a robust and complex package for API authentication. However, most applications do not require the complex features offered by the OAuth2 spec, which can be confusing for both users and developers. In addition, developers have been historically confused about how to authenticate SPA applications or mobile applications using OAuth2 authentication providers like Passport.

SanctumSanctum

OAuth2の複雑さと開発者の混乱に対応するため、ウェブブラウザからのファーストパーティのウェブリクエストとトークンによるAPIリクエストの両方を処理できる、よりシンプルで合理化された認証パッケージの構築に着手しました。この目標は、Laravel Sanctumのリリースにより実現しました。これは、APIに加えてファーストパーティのWeb UIを提供するアプリケーションや、バックエンドLaravelアプリケーションとは別に存在するシングルページアプリケーション(SPA)や、モバイルクライアントを提供するアプリケーションに推奨される認証パッケージと考えてください。In response to the complexity of OAuth2 and developer confusion, we set out to build a simpler, more streamlined authentication package that could handle both first-party web requests from a web browser and API requests via tokens. This goal was realized with the release of Laravel Sanctum[/docs/{{version}}/sanctum], which should be considered the preferred and recommended authentication package for applications that will be offering a first-party web UI in addition to an API, or will be powered by a single-page application (SPA) that exists separately from the backend Laravel application, or applications that offer a mobile client.

Laravel Sanctumは、アプリケーションの認証プロセス全体を管理できるWeb/APIハイブリッド認証パッケージです。これが可能なのは、Sanctumベースのアプリケーションがリクエストを受信すると、Sanctumは最初に認証済みセッションを参照するセッションクッキーがリクエストに含まれているかどうかを判断するからです。Sanctumは、すでに説明したLaravelの組み込み認証サービスを呼び出すことでこれを実現します。リクエストがセッションクッキーを介して認証されていない場合、SanctumはリクエストのAPIトークンを検査します。APIトークンが存在する場合、Sanctumはそのトークンを使用してリクエストを認証します。このプロセスの詳細については、Sanctumの「仕組み」のドキュメントを参照してください。Laravel Sanctum is a hybrid web / API authentication package that can manage your application's entire authentication process. This is possible because when Sanctum based applications receive a request, Sanctum will first determine if the request includes a session cookie that references an authenticated session. Sanctum accomplishes this by calling Laravel's built-in authentication services which we discussed earlier. If the request is not being authenticated via a session cookie, Sanctum will inspect the request for an API token. If an API token is present, Sanctum will authenticate the request using that token. To learn more about this process, please consult Sanctum's "how it works"[/docs/{{version}}/sanctum#how-it-works] documentation.

Laravel Sanctumは、Laravel Jetstream和訳)(和文)アプリケーションスターターキットに含めることを私たちが選択したAPIパッケージです。なぜなら、これはWebアプリケーションの認証ニーズの大部分に最適であると考えているためです。Laravel Sanctum is the API package we have chosen to include with the Laravel Jetstream[https://jetstream.laravel.com] application starter kit because we believe it is the best fit for the majority of web application's authentication needs.

要約とスタックの選択Summary & Choosing Your Stack

要約すると、アプリケーションがブラウザを使用してアクセスされる、モノリシックなLaravelアプリケーションを構築している場合は、アプリケーションにLaravelの組み込み認証サービスを使用してください。In summary, if your application will be accessed using a browser and you are building a monolithic Laravel application, your application will use Laravel's built-in authentication services.

次に、アプリケーションがサードパーティによって使用されるAPIを提供している場合は、PassportまたはSanctumのどちらかを選んでください。アプリケーションにAPIトークン認証を提供します。一般に、Sanctumは、API認証、SPA認証、さらに「スコープ(socpe)」や「能力(ability)」のサポートを含むモバイル認証のためのシンプルで完全なソリューションであるため、使える場合はこちらを推奨します。Next, if your application offers an API that will be consumed by third parties, you will choose between Passport[/docs/{{version}}/passport] or Sanctum[/docs/{{version}}/sanctum] to provide API token authentication for your application. In general, Sanctum should be preferred when possible since it is a simple, complete solution for API authentication, SPA authentication, and mobile authentication, including support for "scopes" or "abilities".

Laravelをバックエンドで利用するシングルページアプリケーション(SPA)を構築している場合は、Laravel Sanctumを使用するべきでしょう。Sanctumを使用する場合は、独自のバックエンド認証ルートを手動で実装するか、Laravel Fortifyをユーザー登録、パスワードのリセット、メールの検証などの機能のためのルートとコントローラを提供するヘッドレス認証バックエンドサービスとして利用する必要があります。If you are building a single-page application (SPA) that will be powered by a Laravel backend, you should use Laravel Sanctum[/docs/{{version}}/sanctum]. When using Sanctum, you will either need to manually implement your own backend authentication routes[#authenticating-users] or utilize Laravel Fortify[/docs/{{version}}/fortify] as a headless authentication backend service that provides routes and controllers for features such as registration, password reset, email verification, and more.

パスポートは、アプリケーションがOAuth2仕様によって提供されるすべての機能を絶対に必要とする場合に選択できます。Passport may be chosen when your application absolutely needs all of the features provided by the OAuth2 specification.

また、すぐに始めたい場合はLaravelの人気のある認証スタックと組み込みの認証サービス、LaravelSanctumをあらかじめ使用し、新しいLaravelアプリケーションをすばやく開始する方法として、Laravel Jetstream和訳)(和文)をおすすめします。。And, if you would like to get started quickly, we are pleased to recommend Laravel Jetstream[https://jetstream.laravel.com] as a quick way to start a new Laravel application that already uses our preferred authentication stack of Laravel's built-in authentication services and Laravel Sanctum.

認証クイックスタートAuthentication Quickstart

Note: note ドキュメントのこの部分では、Laravelアプリケーションスターターキットを介したユーザーの認証について説明します。これには、すばやく開始するのに便利なUIスカフォールドが含まれています。Laravelの認証システムを直接統合したい場合は、ユーザーの手動認証に関するドキュメントを確認してください。{note} This portion of the documentation discusses authenticating users via the Laravel application starter kits[/docs/{{version}}/starter-kits], which includes UI scaffolding to help you get started quickly. If you would like to integrate with Laravel's authentication systems directly, check out the documentation on manually authenticating users[#authenticating-users].

スターターキットのインストールInstall A Starter Kit

まず、Laravelアプリケーションスターターキットをインストールする必要があります。現在のスターターキットであるLaravel BreezeとLaravel Jetstreamは、認証を新しいLaravelアプリケーションへ組み込むために美しく設計された開始点を提供します。First, you should install a Laravel application starter kit[/docs/{{version}}/starter-kits]. Our current starter kits, Laravel Breeze and Laravel Jetstream, offer beautifully designed starting points for incorporating authentication into your fresh Laravel application.

Laravel Breezeは、ログイン、ユーザー登録、パスワードリセット、メールの確認、パスワードの確認など、Laravelのすべての認証機能の最小限でシンプルな実装です。Laravel Breezeのビューレイヤーは、Tailwind CSSを用いスタイル設定されたシンプルなBladeテンプレートで構成しています。さらにBreezeは、VueやReactを使ったInertiaベースのスカフォールドオプションも用意しています。Laravel Breeze is a minimal, simple implementation of all of Laravel's authentication features, including login, registration, password reset, email verification, and password confirmation. Laravel Breeze's view layer is made up of simple Blade templates[/docs/{{version}}/blade] styled with Tailwind CSS[https://tailwindcss.com]. Breeze also offers an Inertia[https://inertiajs.com] based scaffolding option using Vue or React.

Laravel Jetstream和訳)は、Livewire和訳)かInertia.jsとVueを使用する、アプリケーションのスカフォールドのサポートを含む、より堅牢なアプリケーションスターターキットです。さらに、Jetstreamはオプションとして2要素認証、チーム、プロファイル管理、ブラウザセッション管理、Laravel Sanctumを介するAPIサポート、アカウント削除などのサポートを備えています。Laravel Jetstream[https://jetstream.laravel.com] is a more robust application starter kit that includes support for scaffolding your application with Livewire[https://laravel-livewire.com] or Inertia.js and Vue[https://inertiajs.com]. In addition, Jetstream features optional support for two-factor authentication, teams, profile management, browser session management, API support via Laravel Sanctum[/docs/{{version}}/sanctum], account deletion, and more.

認証済みユーザー取得Retrieving The Authenticated User

認証スターターキットをインストールし、ユーザーがアプリケーションへ登録・認証できるようにした後、多くの場合は現在認証済みのユーザーを操作する必要があります。受信リクエストの処理時、Authファサードのuserメソッドを使用して認証済みユーザーにアクセスできます。After installing an authentication starter kit and allowing users to register and authenticate with your application, you will often need to interact with the currently authenticated user. While handling an incoming request, you may access the authenticated user via the Auth facade's user method:

use Illuminate\Support\Facades\Auth;

// 現在認証しているユーザーを取得
$user = Auth::user();

// 現在認証しているユーザーのIDを取得
$id = Auth::id();

別の方法として、ユーザーが一度認証されると、Illuminate\Http\Requestインスタンスを介してその認証済みユーザーへアクセスできます。タイプヒントクラスは、コントローラメソッドに自動的に依存注入されることを忘れないでください。Illuminate\Http\Requestオブジェクトをタイプヒントすることで、リクエストのuserメソッドを介しアプリケーションのどのコントローラメソッドからも、認証済みユーザーへ便利にアクセスできます。Alternatively, once a user is authenticated, you may access the authenticated user via an Illuminate\Http\Request instance. Remember, type-hinted classes will automatically be injected into your controller methods. By type-hinting the Illuminate\Http\Request object, you may gain convenient access to the authenticated user from any controller method in your application via the request's user method:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FlightController extends Controller
{
    /**
     * 既存のフライトの情報を更新
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        // $request->user()
    }
}

現在のユーザーが認証済みか判定Determining If The Current User Is Authenticated

受信HTTPリクエストを送ったユーザーが認証されているかを判断するには、Authファサードでcheckメソッドを使用します。ユーザーが認証されている場合、このメソッドはtrueを返します。To determine if the user making the incoming HTTP request is authenticated, you may use the check method on the Auth facade. This method will return true if the user is authenticated:

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // ユーザーはログイン済み
}

lightbulb">Tip!! checkメソッドを使用してユーザーが認証されているかどうかを判定できますが、通常はミドルウェアを使用して、ユーザーに特定のルート/コントローラへのアクセスを許す前に、ユーザーが認証されていることを確認します。これについて詳しくは、ルートの保護に関するドキュメントをご覧ください。{tip} Even though it is possible to determine if a user is authenticated using the check method, you will typically use a middleware to verify that the user is authenticated before allowing the user access to certain routes / controllers. To learn more about this, check out the documentation on protecting routes[/docs/{{version}}/authentication#protecting-routes].

ルートの保護Protecting Routes

ルートミドルウェアは、認証済みユーザーのみが特定のルートへアクセスできるように、制限するため使用します。LaravelはIlluminate\Auth\Middleware\Authenticateクラスを参照するauthミドルウェアを用意しています。このミドルウェアはあらかじめ、アプリケーションのHTTPカーネルに登録されているため、必要なのはミドルウェアをルート定義に指定することだけです。Route middleware[/docs/{{version}}/middleware] can be used to only allow authenticated users to access a given route. Laravel ships with an auth middleware, which references the Illuminate\Auth\Middleware\Authenticate class. Since this middleware is already registered in your application's HTTP kernel, all you need to do is attach the middleware to a route definition:

Route::get('/flights', function () {
    // 認証済みユーザーのみがこのルートにアクセス可能
})->middleware('auth');

認証されていないユーザーのリダイレクトRedirecting Unauthenticated Users

authミドルウェアが認証されていないユーザーを検出すると、ユーザーをlogin 名前付きルートにリダイレクトします。この動作は、アプリケーションのapp/Http/Middleware/Authenticate.phpファイルのredirectTo関数を更新することで変更できます。When the auth middleware detects an unauthenticated user, it will redirect the user to the login named route[/docs/{{version}}/routing#named-routes]. You may modify this behavior by updating the redirectTo function in your application's app/Http/Middleware/Authenticate.php file:

/**
 * ユーザーをリダイレクトするパスの取得
 *
 * @param  \Illuminate\Http\Request  $request
 * @return string
 */
protected function redirectTo($request)
{
    return route('login');
}

ガードの指定Specifying A Guard

authミドルウェアをルートへ接続するときに、ユーザーの認証に使用する「ガード」を指定することもできます。指定するガードは、auth.php設定ファイルのguards配列内のキーの1つに対応している必要があります。When attaching the auth middleware to a route, you may also specify which "guard" should be used to authenticate the user. The guard specified should correspond to one of the keys in the guards array of your auth.php configuration file:

Route::get('/flights', function () {
    // 認証済みユーザーのみがこのルートにアクセスできます
})->middleware('auth:admin');

ログイン回数制限Login Throttling

Laravel BreezeまたはLaravel Jetstream スターターキットを使用している場合、ログインの試行へレート制限が自動的に適用されます。デフォルトでは、ユーザーが数回試行した後に正しい資格情報を提供できなかった場合、ユーザーは1分間ログインできません。ログインの回数制限は、ユーザーのユーザー名/メールアドレスとIPアドレスの組み合わせごとに制限します。If you are using the Laravel Breeze or Laravel Jetstream starter kits[/docs/{{version}}/starter-kits], rate limiting will automatically be applied to login attempts. By default, the user will not be able to login for one minute if they fail to provide the correct credentials after several attempts. The throttling is unique to the user's username / email address and their IP address.

lightbulb">Tip!! アプリケーション内の他のルートのレート制限を希望する場合は、レート制限のドキュメントを確認してください。{tip} If you would like to rate limit other routes in your application, check out the rate limiting documentation[/docs/{{version}}/routing#rate-limiting].

ユーザーを手動で認証するManually Authenticating Users

Laravelのアプリケーションスターターキットに含まれている認証スカフォールドを必ず使用する必要はありません。このスカフォールドを使用しないことを選択した場合は、Laravel認証クラスを直接使用してユーザー認証を管理する必要があります。心配ありません。簡単です!You are not required to use the authentication scaffolding included with Laravel's application starter kits[/docs/{{version}}/starter-kits]. If you choose not to use this scaffolding, you will need to manage user authentication using the Laravel authentication classes directly. Don't worry, it's a cinch!

Auth ファサードを介してLaravelの認証サービスにアクセスできるように、クラスの最初でAuthファサードを必ずインポートする必要があります。次に、attemptメソッドを見てみましょう。attemptメソッドは通常、アプリケーションの「ログイン」フォームからの認証試行を処理するために使用されます。認証が成功した場合は、ユーザーのセッションを再生成して、セッション固定攻撃を防ぐ必要があります。We will access Laravel's authentication services via the Auth facade[/docs/{{version}}/facades], so we'll need to make sure to import the Auth facade at the top of the class. Next, let's check out the attempt method. The attempt method is normally used to handle authentication attempts from your application's "login" form. If authentication is successful, you should regenerate the user's session[/docs/{{version}}/session] to prevent session fixation[https://en.wikipedia.org/wiki/Session_fixation]:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * 認証の試行を処理
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function authenticate(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            return redirect()->intended('dashboard');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ]);
    }
}

attemptメソッドは、最初の引数にキー/値ペアの配列を受け入れます。配列の値はデータベーステーブルでユーザーを見つけるために使用します。したがって、上例でユーザーは、emailカラムの値により取得されます。ユーザーが見つかった場合、データベースに保存しているハッシュ化したパスワードと、配列でメソッドに渡したpassword値を比較します。フレームワークはデータベース内のハッシュ化したパスワードと比較する前に値を自動的にハッシュするため、受信リクエストのpassword値はハッシュしないでください。2つのハッシュ化されたパスワードが一致した場合、ユーザーの認証セッションを開始します。The attempt method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column. If the user is found, the hashed password stored in the database will be compared with the password value passed to the method via the array. You should not hash the incoming request's password value, since the framework will automatically hash the value before comparing it to the hashed password in the database. An authenticated session will be started for the user if the two hashed passwords match.

Laravelの認証サービスは、認証ガードの「プロバイダ」設定に基づいてデータベースからユーザーを取得することを忘れないでください。デフォルトの config/auth.php設定ファイルでは、Eloquentユーザープロバイダが指定されており、ユーザーを取得するときにApp\Models\Userモデルを使用するように指示されています。アプリケーションの必要に基づいて、設定ファイル内のこうした値を変更できます。Remember, Laravel's authentication services will retrieve users from your database based on your authentication guard's "provider" configuration. In the default config/auth.php configuration file, the Eloquent user provider is specified and it is instructed to use the App\Models\User model when retrieving users. You may change these values within your configuration file based on the needs of your application.

認証が成功した場合、attemptメソッドはtrueを返します。それ以外の場合は、falseが返します。The attempt method will return true if authentication was successful. Otherwise, false will be returned.

Laravelのリダイレクタが提供するintendedメソッドは、認証ミドルウェアによってインターセプトされる前に、アクセスしようとしたURLへユーザーをリダイレクトします。目的の行き先が使用できない場合のために、このメソッドにはフォールバックURIが指定できます。The intended method provided by Laravel's redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.

追加条件の指定Specifying Additional Conditions

必要に応じて、ユーザーのメールアドレスとパスワードに加え、認証クエリにクエリ条件を追加することもできます。これのためには、attemptメソッドへ渡す配列にクエリ条件を追加するだけです。たとえば、ユーザーが「アクティブ(active)」としてマークされていることを確認できます。If you wish, you may also add extra query conditions to the authentication query in addition to the user's email and password. To accomplish this, we may simply add the query conditions to the array passed to the attempt method. For example, we may verify that the user is marked as "active":

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // 認証に成功した
}

Note: note これらの例では、emailは必須オプションではなく、単に例として使用しています。データベーステーブルの"username"に対応するカラム名を使用する必要があります。{note} In these examples, email is not a required option, it is merely used as an example. You should use whatever column name corresponds to a "username" in your database table.

特定のガードインスタンスへのアクセスAccessing Specific Guard Instances

Authファサードのguardメソッドを介して、ユーザーを認証するときに利用するガードインスタンスを指定できます。これにより、完全に分離した認証可能なモデルやユーザーテーブルを使用して、アプリケーションの個別の部分での認証を管理できます。Via the Auth facade's guard method, you may specify which guard instance you would like to utilize when authenticating the user. This allows you to manage authentication for separate parts of your application using entirely separate authenticatable models or user tables.

guardメソッドへ渡たすガード名は、auth.php設定ファイルで設定するガードの1つに対応している必要があります。The guard name passed to the guard method should correspond to one of the guards configured in your auth.php configuration file:

if (Auth::guard('admin')->attempt($credentials)) {
    // ...
}

持続ログインRemembering Users

多くのWebアプリケーションでは、ログインフォームに「継続ログイン(remember me)」チェックボックスがあります。アプリケーションで「継続ログイン」機能を提供したい場合は、attemptメソッドの2番目の引数としてブール値を渡すことができます。Many web applications provide a "remember me" checkbox on their login form. If you would like to provide "remember me" functionality in your application, you may pass a boolean value as the second argument to the attempt method.

この値がtrueの場合、Laravelはユーザーを無期限に、または手動でログアウトするまで認証されたままにします。 usersテーブルには、「継続ログイン(remember me)」トークンを格納するために使用される文字列、remember_tokenカラムを含める必要があります。新しいLaravelアプリケーションに含まれている usersテーブルのマイグレーションには、すでにこのカラムが含まれています。When this value is true, Laravel will keep the user authenticated indefinitely or until they manually logout. Your users table must include the string remember_token column, which will be used to store the "remember me" token. The users table migration included with new Laravel applications already includes this column:

use Illuminate\Support\Facades\Auth;

if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
    // $rememberがtrueならユーザーは持続ログインされる
}

他の認証方法Other Authentication Methods

ユーザーインスタンスの認証Authenticate A User Instance

既存のユーザーインスタンスを現在認証されているユーザーとして設定する必要がある場合は、ユーザーインスタンスをAuthファサードのloginメソッドに渡すことができます。指定されたユーザーインスタンスは、Illuminate\Contracts\Auth\Authenticatable契約の実装である必要があります。Laravelに含まれているApp\Models\Userモデルは前もってこのインターフェイスを実装しています。この認証方法は、ユーザーがアプリケーションに登録した直後など、すでに有効なユーザーインスタンスがある場合に役立ちます。If you need to set an existing user instance as the currently authenticated user, you may pass the user instance to the Auth facade's login method. The given user instance must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract[/docs/{{version}}/contracts]. The App\Models\User model included with Laravel already implements this interface. This method of authentication is useful when you already have a valid user instance, such as directly after a user registers with your application:

use Illuminate\Support\Facades\Auth;

Auth::login($user);

loginメソッドの2番目の引数へ論理値を渡たせます。この値は、認証されたセッションに「継続ログイン(remember me)」機能が必要かどうかを示します。これはセッションが無期限に、またはユーザーがアプリケーションから自分でログアウトするまで認証され続けることを意味します。You may pass a boolean value as the second argument to the login method. This value indicates if "remember me" functionality is desired for the authenticated session. Remember, this means that the session will be authenticated indefinitely or until the user manually logs out of the application:

Auth::login($user, $remember = true);

必要に応じて、loginメソッドを呼び出す前に認証ガードを指定できます。If needed, you may specify an authentication guard before calling the login method:

Auth::guard('admin')->login($user);

IDによるユーザー認証Authenticate A User By ID

データベースレコードの主キーを使用してユーザーを認証するには、loginUsingIdメソッドを使用できます。このメソッドは、認証するユーザーの主キーを引数に取ります。To authenticate a user using their database record's primary key, you may use the loginUsingId method. This method accepts the primary key of the user you wish to authenticate:

Auth::loginUsingId(1);

loginUsingIdメソッドの第2引数として論理値を渡すことができます。この値は、認証されたセッションに「継続ログイン(remember me)」機能が必要かどうかを示します。これはセッションが無期限に、またはユーザーがアプリケーションから自分でログアウトするまで認証され続けることを意味します。You may pass a boolean value as the second argument to the loginUsingId method. This value indicates if "remember me" functionality is desired for the authenticated session. Remember, this means that the session will be authenticated indefinitely or until the user manually logs out of the application:

Auth::loginUsingId(1, $remember = true);

ユーザーを1回認証するAuthenticate A User Once

onceメソッドを使用して、そのリクエスト1回だけアプリケーションでユーザーを認証できます。このメソッドを呼び出すときは、セッションやクッキーを使用しません。You may use the once method to authenticate a user with the application for a single request. No sessions or cookies will be utilized when calling this method:

if (Auth::once($credentials)) {
    //
}

HTTP基本認証HTTP Basic Authentication

HTTP基本認証は、専用の「ログイン」ページを設定せずに、アプリケーションのユーザーを認証する簡単な方法を提供します。使用するには、auth.basicミドルウェアをルートに指定します。auth.basicミドルウェアはLaravelフレームワークに含まれているため、定義する必要はありません。HTTP Basic Authentication[https://en.wikipedia.org/wiki/Basic_access_authentication] provides a quick way to authenticate users of your application without setting up a dedicated "login" page. To get started, attach the auth.basic middleware[/docs/{{version}}/middleware] to a route. The auth.basic middleware is included with the Laravel framework, so you do not need to define it:

Route::get('/profile', function () {
    // 認証されたユーザーのみがこのルートにアクセスできる
})->middleware('auth.basic');

このミドルウェアがルートに接続されると、ブラウザでそのルートへアクセスするときにログイン情報の入力が自動的に求められます。デフォルトでは、auth.basicミドルウェアは、usersデータベーステーブルのemailカラムがユーザーの"username"であると想定します。Once the middleware has been attached to the route, you will automatically be prompted for credentials when accessing the route in your browser. By default, the auth.basic middleware will assume the email column on your users database table is the user's "username".

FastCGIに関する注記A Note On FastCGI

PHPFastCGIとApacheを使用してLaravelアプリケーションを提供している場合、HTTP基本認証は正しく機能しない可能性があります。これらの問題を修正するために、アプリケーションの.htaccessファイルに次の行を追加できます。If you are using PHP FastCGI and Apache to serve your Laravel application, HTTP Basic authentication may not work correctly. To correct these problems, the following lines may be added to your application's .htaccess file:

RewriteCond %{HTTP:Authorization} ^(. )$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

ステートレスなHTTP基本認証Stateless HTTP Basic Authentication

セッションでユーザー識別子クッキーを設定せずにHTTP基本認証を使用することもできます。これは主に、HTTP認証を使用してアプリケーションのAPIへの要求を認証することを選択した場合に役立ちます。これを実現するには、onceBasicメソッドを呼び出すミドルウェアを定義します。onceBasicメソッドによってレスポンスが返されない場合、そのリクエストはさらにアプリケーションに渡されます。You may also use HTTP Basic Authentication without setting a user identifier cookie in the session. This is primarily helpful if you choose to use HTTP Authentication to authenticate requests to your application's API. To accomplish this, define a middleware[/docs/{{version}}/middleware] that calls the onceBasic method. If no response is returned by the onceBasic method, the request may be passed further into the application:

<?php

namespace App\Http\Middleware;

use Illuminate\Support\Facades\Auth;

class AuthenticateOnceWithBasicAuth
{
    /**
     * 受信リクエストの処理
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, $next)
    {
        return Auth::onceBasic() ?: $next($request);
    }

}

次に、ルートミドルウェアを登録して、ルートに指定します。Next, register the route middleware[/docs/{{version}}/middleware#registering-middleware] and attach it to a route:

Route::get('/api/user', function () {
    // 認証済みユーザーのみ、このルートにアクセスできる
})->middleware('auth.basic.once');

ログアウトLogging Out

アプリケーションからユーザーを手動でログアウトするには、Authファサードが提供するlogoutメソッドを使用できます。これにより、ユーザーのセッションから認証情報が削除され、以降のリクエストが認証されなくなります。To manually log users out of your application, you may use the logout method provided by the Auth facade. This will remove the authentication information from the user's session so that subsequent requests are not authenticated.

logoutメソッドを呼び出すことに加えて、ユーザーのセッションを無効にして、CSRFトークンを再生成することを推奨します。ユーザーをログアウトした後、通常はユーザーをアプリケーションのルートにリダイレクトします。In addition to calling the logout method, it is recommended that you invalidate the user's session and regenerate their CSRF token[/docs/{{version}}/csrf]. After logging the user out, you would typically redirect the user to the root of your application:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

/**
 * ユーザーをアプリケーションからログアウトさせる
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function logout(Request $request)
{
    Auth::logout();

    $request->session()->invalidate();

    $request->session()->regenerateToken();

    return redirect('/');
}

他のデバイスでのセッションの無効化Invalidating Sessions On Other Devices

Laravelは、現在のデバイスのセッションを無効にすることなく、他のデバイスでアクティブなそのユーザーのセッションを無効にして「ログアウト」するためのメカニズムも提供しています。この機能は通常、ユーザーがパスワードを変更または更新していて、現在のデバイスを認証したまま他のデバイスのセッションを無効にしたい状況で使用します。Laravel also provides a mechanism for invalidating and "logging out" a user's sessions that are active on other devices without invalidating the session on their current device. This feature is typically utilized when a user is changing or updating their password and you would like to invalidate sessions on other devices while keeping the current device authenticated.

開始する前に、Illuminate\Session\Middleware\AuthenticationSessionミドルウェアが存在し、App\Http\Kernelクラスの'webミドルウェアグループがアンコメントされているのを確認する必要があります。Before getting started, you should make sure that the Illuminate\Session\Middleware\AuthenticateSession middleware is present and un-commented in your App\Http\Kernel class' web middleware group:

'web' => [
    // ...
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    // ...
],

次に、Authファサードが提供するlogoutOtherDevicesメソッドを使用します。このメソッドは、アプリケーションが入力フォームから受け入れた、ユーザーの現在のパスワードを確認する必要があります。Then, you may use the logoutOtherDevices method provided by the Auth facade. This method requires the user to confirm their current password, which your application should accept through an input form:

use Illuminate\Support\Facades\Auth;

Auth::logoutOtherDevices($currentPassword);

logoutOtherDevicesメソッドが呼び出されると、そのユーザーの他のセッションは完全に無効になります。つまり、以前に認証されたすべてのガードから「ログアウト」されます。When the logoutOtherDevices method is invoked, the user's other sessions will be invalidated entirely, meaning they will be "logged out" of all guards they were previously authenticated by.

パスワードの確認Password Confirmation

アプリケーションの構築中、あるアクションを実行させる前、またはユーザーをアプリケーションの機密領域へリダイレクトする前に、ユーザーへパスワードを確認してもらうアクションの発生する場面がしばし起こるでしょう。Laravelはこの行程を簡単にするためのミドルウェアが組み込まれています。この機能を実装するには、2つのルートを定義する必要があります。1つはユーザーにパスワードの確認を求めるビューを表示するルート、もう1つはパスワードの有効性を確認後、ユーザーを目的の行き先にリダイレクトするルートです。While building your application, you may occasionally have actions that should require the user to confirm their password before the action is performed or before the user is redirected to a sensitive area of the application. Laravel includes built-in middleware to make this process a breeze. Implementing this feature will require you to define two routes: one route to display a view asking the user to confirm their password and another route to confirm that the password is valid and redirect the user to their intended destination.

lightbulb">Tip!! 次のドキュメントでは、Laravelのパスワード確認機能を直接統合する方法について説明しています。ただし、もっと早く始めたい場合は、Laravelアプリケーションスターターキットにこの機能のサポートが含まれています!{tip} The following documentation discusses how to integrate with Laravel's password confirmation features directly; however, if you would like to get started more quickly, the Laravel application starter kits[/docs/{{version}}/starter-kits] include support for this feature!

設定Configuration

パスワードを確認したら、ユーザーはその後3時間パスワードを再確認するように求められることはありません。ただし、アプリケーションのconfig/auth.php設定ファイル内のpassword_timeout設定値の値を変更することにより、ユーザーがパスワードの再入力を求められるまでの時間を設定できます。After confirming their password, a user will not be asked to confirm their password again for three hours. However, you may configure the length of time before the user is re-prompted for their password by changing the value of the password_timeout configuration value within your application's config/auth.php configuration file.

ルーティングRouting

パスワード確認フォームThe Password Confirmation Form

まず、ユーザーにパスワードの確認を要求するビューを表示するルートを定義します。First, we will define a route to display a view that requests the user to confirm their password:

Route::get('/confirm-password', function () {
    return view('auth.confirm-password');
})->middleware('auth')->name('password.confirm');

ご想像のとおり、このルートによって返されるビューには、passwordフィールドを含むフォームが必要です。さらに、ユーザーがアプリケーションの保護された領域に入ろうとしているため、パスワードを確認する必要があることを説明する、お好みなテキストをビュー内に含めてください。As you might expect, the view that is returned by this route should have a form containing a password field. In addition, feel free to include text within the view that explains that the user is entering a protected area of the application and must confirm their password.

パスワードの確認Confirming The Password

次に、「パスワードの確認」ビューからのフォーム要求を処理するルートを定義します。このルートはパスワードを検証し、ユーザーを目的の行き先にリダイレクトする責任を負っています。Next, we will define a route that will handle the form request from the "confirm password" view. This route will be responsible for validating the password and redirecting the user to their intended destination:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;

Route::post('/confirm-password', function (Request $request) {
    if (! Hash::check($request->password, $request->user()->password)) {
        return back()->withErrors([
            'password' => ['The provided password does not match our records.']
        ]);
    }

    $request->session()->passwordConfirmed();

    return redirect()->intended();
})->middleware(['auth', 'throttle:6,1']);

先へ進む前に、このルートをさらに詳しく調べてみましょう。まず、リクエストのpasswordフィールドが、認証済みユーザーのパスワードと実際に一致するか判定されます。パスワードが有効な場合、ユーザーがパスワードを確認したことをLaravelのセッションに通知する必要があります。passwordConfirmedメソッドは、ユーザーのセッションにタイムスタンプを設定します。このタイムスタンプを使用して、ユーザーが最後にパスワードを確認した日時をLaravelは判別できます。最後に、ユーザーを目的の行き先にリダイレクトします。Before moving on, let's examine this route in more detail. First, the request's password field is determined to actually match the authenticated user's password. If the password is valid, we need to inform Laravel's session that the user has confirmed their password. The passwordConfirmed method will set a timestamp in the user's session that Laravel can use to determine when the user last confirmed their password. Finally, we can redirect the user to their intended destination.

パスワード確認済みルートの保護Protecting Routes

最近パスワード確認を済ませたことが必要なアクションを実行するすべてのルートに、password.confirmミドルウェアが割り当てられていることを確認する必要があります。このミドルウェアはLaravelのデフォルトインストールに含まれており、ユーザーがパスワードを確認した後にその場所へリダイレクトされるように、ユーザーの意図した行き先をセッションに自動的に保存します。ユーザーの意図した行き先をセッションに保存した後、ミドルウェアはユーザーをpassword.confirm名前付きルートにリダイレクトします。You should ensure that any route that performs an action which requires recent password confirmation is assigned the password.confirm middleware. This middleware is included with the default installation of Laravel and will automatically store the user's intended destination in the session so that the user may be redirected to that location after confirming their password. After storing the user's intended destination in the session, the middleware will redirect the user to the password.confirm named route[/docs/{{version}}/routing#named-routes]:

Route::get('/settings', function () {
    // ...
})->middleware(['password.confirm']);

Route::post('/settings', function () {
    // ...
})->middleware(['password.confirm']);

カスタムガードの追加Adding Custom Guards

Authファサードのextendメソッドを使用して独自の認証ガードを定義できます。サービスプロバイダ内のextendメソッドを呼び出す必要があります。LaravelにははじめからAuthServiceProviderが付属しているため、そのプロバイダにコードを配置できます。You may define your own authentication guards using the extend method on the Auth facade. You should place your call to the extend method within a service provider[/docs/{{version}}/providers]. Since Laravel already ships with an AuthServiceProvider, we can place the code in that provider:

<?php

namespace App\Providers;

use App\Services\Auth\JwtGuard;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Auth;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * 全認証/認可サービスの登録
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Auth::extend('jwt', function ($app, $name, array $config) {
            // Illuminate\Contracts\Auth\Guardインスタンスを返す…

            return new JwtGuard(Auth::createUserProvider($config['provider']));
        });
    }
}

上記の例でわかるように、extendメソッドへ渡たすコールバックは、Illuminate\Contracts\Auth\Guardの実装を返す必要があります。このインターフェイスには、カスタムガードを定義するために実装する必要のあるメソッドがいくつか含まれています。カスタムガードを定義したら、auth.php設定ファイルのguards設定でそのガードを参照します。As you can see in the example above, the callback passed to the extend method should return an implementation of Illuminate\Contracts\Auth\Guard. This interface contains a few methods you will need to implement to define a custom guard. Once your custom guard has been defined, you may reference the guard in the guards configuration of your auth.php configuration file:

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

クロージャリクエストガードClosure Request Guards

カスタムHTTPリクエストベースの認証システムを実装する最も簡単な方法は、Auth::viaRequestメソッドを使用することです。この方法は、単一クロージャを使用して認証プロセスをすばやく定義できます。The simplest way to implement a custom, HTTP request based authentication system is by using the Auth::viaRequest method. This method allows you to quickly define your authentication process using a single closure.

利用するには、AuthServiceProviderbootメソッド内でAuth::viaRequestメソッドを呼び出します。viaRequestメソッドは、最初の引数として認証ドライバー名を受け入れます。この名前には、カスタムガードを説明する任意の文字列を指定できます。メソッドに渡たす2番目の引数は、やってきたHTTPリクエストを受信し、ユーザーインスタンスを返すクロージャである必要があります。認証が失敗した場合は、nullを返します。To get started, call the Auth::viaRequest method within the boot method of your AuthServiceProvider. The viaRequest method accepts an authentication driver name as its first argument. This name can be any string that describes your custom guard. The second argument passed to the method should be a closure that receives the incoming HTTP request and returns a user instance or, if authentication fails, null:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

/**
 * 全認証/認可サービスの登録
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Auth::viaRequest('custom-token', function (Request $request) {
        return User::where('token', $request->token)->first();
    });
}

カスタム認証ドライバーを定義したら、auth.php設定ファイルのguards設定でドライバーとして指定します。Once your custom authentication driver has been defined, you may configure it as a driver within the guards configuration of your auth.php configuration file:

'guards' => [
    'api' => [
        'driver' => 'custom-token',
    ],
],

カスタムユーザープロバイダの追加Adding Custom User Providers

従来のリレーショナルデータベースを使用してユーザーを保存していない場合は、独自の認証ユーザープロバイダでLaravelを拡張する必要があります。Authファサードでproviderメソッドを使用して、カスタムユーザープロバイダを定義します。ユーザープロバイダリゾルバは、Illuminate\Contracts\Auth\UserProviderの実装を返す必要があります。If you are not using a traditional relational database to store your users, you will need to extend Laravel with your own authentication user provider. We will use the provider method on the Auth facade to define a custom user provider. The user provider resolver should return an implementation of Illuminate\Contracts\Auth\UserProvider:

<?php

namespace App\Providers;

use App\Extensions\MongoUserProvider;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Auth;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * 全認証/認可サービスの登録
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Auth::provider('mongo', function ($app, array $config) {
            // Illuminate\Contracts\Auth\UserProviderのインスタンスを返す…

            return new MongoUserProvider($app->make('mongo.connection'));
        });
    }
}

providerメソッドを使用してプロバイダを登録した後、auth.php設定ファイルで新しいユーザープロバイダに切り替えてください。まず、新しいドライバーを使用するproviderを定義します。After you have registered the provider using the provider method, you may switch to the new user provider in your auth.php configuration file. First, define a provider that uses your new driver:

'providers' => [
    'users' => [
        'driver' => 'mongo',
    ],
],

最後に、guards設定でこのプロバイダを参照します。Finally, you may reference this provider in your guards configuration:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
],

ユーザープロバイダ契約The User Provider Contract

Illuminate\Contracts\Auth\UserProviderの実装は、MySQLやMongoDBなどの永続ストレージシステムからIlluminate\Contracts\Auth\Authenticatable実装をフェッチする責務を持っています。これら2つのインターフェイスにより、ユーザーデータの保存方法や、認証されたユーザーを表すために使用されるクラスのタイプに関係なく、Laravel認証メカニズムは機能し続けられます。Illuminate\Contracts\Auth\UserProvider implementations are responsible for fetching an Illuminate\Contracts\Auth\Authenticatable implementation out of a persistent storage system, such as MySQL, MongoDB, etc. These two interfaces allow the Laravel authentication mechanisms to continue functioning regardless of how the user data is stored or what type of class is used to represent the authenticated user:

Illuminate\Contracts\Auth\UserProviderコントラクトを見てみましょう。Let's take a look at the Illuminate\Contracts\Auth\UserProvider contract:

<?php

namespace Illuminate\Contracts\Auth;

interface UserProvider
{
    public function retrieveById($identifier);
    public function retrieveByToken($identifier, $token);
    public function updateRememberToken(Authenticatable $user, $token);
    public function retrieveByCredentials(array $credentials);
    public function validateCredentials(Authenticatable $user, array $credentials);
}

retrieveById関数は通常、MySQLデータベースからの自動増分IDなど、ユーザーを表すキーを受け取ります。IDに一致するAuthenticatable実装は、このメソッドにより取得され、返えされる必要があります。The retrieveById function typically receives a key representing the user, such as an auto-incrementing ID from a MySQL database. The Authenticatable implementation matching the ID should be retrieved and returned by the method.

retrieveByToken関数は、一意の$identifierと"remember me" $tokenによってユーザーを取得します。通常、これはremember_tokenのようなデータベースカラムに格納されます。前のメソッドと同様に、トークン値が一致するAuthenticatableの実装をこのメソッドは返す必要があります。The retrieveByToken function retrieves a user by their unique $identifier and "remember me" $token, typically stored in a database column like remember_token. As with the previous method, the Authenticatable implementation with a matching token value should be returned by this method.

updateRememberTokenメソッドは、$userインスタンスのremember_tokenを新しい$tokenで更新します。「remember me」認証の試行が成功したとき、またはユーザーがログアウトしているときに、新しいトークンをユーザーに割り当てます。The updateRememberToken method updates the $user instance's remember_token with the new $token. A fresh token is assigned to users on a successful "remember me" authentication attempt or when the user is logging out.

retrieveByCredentialsメソッドは、アプリケーションで認証を試みるときに、Auth::attemptメソッドに渡されたログイン情報の配列を受け取ります。次に、メソッドはこれらのログイン情報に一致するユーザーを永続ストレージへ「クエリ」する必要があります。通常、このメソッドは、``$credentials['username']の値と一致する"username"を持つユーザーレコードを検索する"WHERE"条件でクエリを実行します。このメソッドは、Authenticatable`の実装を返す必要があります。この方法では、パスワードの検証や認証を試みるべきではありません。The retrieveByCredentials method receives the array of credentials passed to the Auth::attempt method when attempting to authenticate with an application. The method should then "query" the underlying persistent storage for the user matching those credentials. Typically, this method will run a query with a "where" condition that searches for a user record with a "username" matching the value of $credentials['username']. The method should return an implementation of Authenticatable. This method should not attempt to do any password validation or authentication.

validateCredentialsメソッドは、指定された$user$credentialsと比較してユーザーを認証する必要があります。たとえば、このメソッドは通常、Hash::checkメソッドを使用して、$user->getAuthPassword()の値を$credentials['password']の値と比較します。このメソッドは、パスワードが有効かどうかを示すtruefalseを返す必要があります。The validateCredentials method should compare the given $user with the $credentials to authenticate the user. For example, this method will typically use the Hash::check method to compare the value of $user->getAuthPassword() to the value of $credentials['password']. This method should return true or false indicating whether the password is valid.

Authenticatable契約The Authenticatable Contract

UserProviderの各メソッドについて説明したので、Authenticatable契約を見てみましょう。ユーザープロバイダは、retrieveByIdretrieveByTokenretrieveByCredentialsメソッドからこのインターフェイスの実装を返す必要があることに注意してください。Now that we have explored each of the methods on the UserProvider, let's take a look at the Authenticatable contract. Remember, user providers should return implementations of this interface from the retrieveById, retrieveByToken, and retrieveByCredentials methods:

<?php

namespace Illuminate\Contracts\Auth;

interface Authenticatable
{
    public function getAuthIdentifierName();
    public function getAuthIdentifier();
    public function getAuthPassword();
    public function getRememberToken();
    public function setRememberToken($value);
    public function getRememberTokenName();
}

このインターフェイスはシンプルです。getAuthIdentifierNameメソッドはユーザーの「主キー」フィールドの名前を返す必要があり、getAuthIdentifierメソッドはユーザーの「主キー」を返す必要があります。MySQLバックエンドを使用する場合、これはユーザーレコードに割り当てられた自動増分の主キーであるでしょう。getAuthPasswordメソッドは、ユーザーのハッシュされたパスワードを返す必要があります。This interface is simple. The getAuthIdentifierName method should return the name of the "primary key" field of the user and the getAuthIdentifier method should return the "primary key" of the user. When using a MySQL back-end, this would likely be the auto-incrementing primary key assigned to the user record. The getAuthPassword method should return the user's hashed password.

このインターフェイスにより、使用しているORMまたはストレージ抽象化レイヤーに関係なく、認証システムは任意の「ユーザー」クラスと連携できます。デフォルトでLaravelはapp/Modelsディレクトリに、このインターフェイスを実装するApp\Models\Userクラスを持っています。This interface allows the authentication system to work with any "user" class, regardless of what ORM or storage abstraction layer you are using. By default, Laravel includes a App\Models\User class in the app/Models directory which implements this interface.

イベントEvents

Laravelは、認証プロセス中にさまざまなイベントをディスパッチします。EventServiceProviderでこれらのイベントにリスナを割り振れます。Laravel dispatches a variety of events[/docs/{{version}}/events] during the authentication process. You may attach listeners to these events in your EventServiceProvider:

/**
 * アプリケーションのイベントリスナマッピング。
 *
 * @var array
 */
protected $listen = [
    'Illuminate\Auth\Events\Registered' => [
        'App\Listeners\LogRegisteredUser',
    ],

    'Illuminate\Auth\Events\Attempting' => [
        'App\Listeners\LogAuthenticationAttempt',
    ],

    'Illuminate\Auth\Events\Authenticated' => [
        'App\Listeners\LogAuthenticated',
    ],

    'Illuminate\Auth\Events\Login' => [
        'App\Listeners\LogSuccessfulLogin',
    ],

    'Illuminate\Auth\Events\Failed' => [
        'App\Listeners\LogFailedLogin',
    ],

    'Illuminate\Auth\Events\Validated' => [
        'App\Listeners\LogValidated',
    ],

    'Illuminate\Auth\Events\Verified' => [
        'App\Listeners\LogVerified',
    ],

    'Illuminate\Auth\Events\Logout' => [
        'App\Listeners\LogSuccessfulLogout',
    ],

    'Illuminate\Auth\Events\CurrentDeviceLogout' => [
        'App\Listeners\LogCurrentDeviceLogout',
    ],

    'Illuminate\Auth\Events\OtherDeviceLogout' => [
        'App\Listeners\LogOtherDeviceLogout',
    ],

    'Illuminate\Auth\Events\Lockout' => [
        'App\Listeners\LogLockout',
    ],

    'Illuminate\Auth\Events\PasswordReset' => [
        'App\Listeners\LogPasswordReset',
    ],
];

章選択

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作