Readouble

Laravel 5.2 認証

イントロダクションIntroduction

Laravelでは簡単に認証が実装できます。実際ほとんど全て最初から設定済みです。認証の設定ファイルはconfig/auth.phpに用意してあり、認証サービスの振る舞いを調整できるように、読みやすいコメント付きでたくさんのオプションが用意されています。Laravel makes implementing authentication very simple. In fact, almost everything is configured for you out of the box. The authentication configuration file is located at config/auth.php, which contains several well documented options for tweaking the behavior of the authentication services.

Laravelの認証機能は「ガード」と「プロバイダ」を中心概念として構成されています。ガードは各リクエストごとに、どのようにユーザを認証するかを定義します。たとえば、Laravelにはセッションストレージとクッキーを使いながら状態を維持するsessionガードと、各リクエストごとに認証をパスさせるための「APIトークン」を使用したユーザ認証を行うtokenガードが用意されています。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 and a token guard, which authenticates users using a "API token" that is passed with each request.

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

混乱しても心配ありません。通常のアプリケーションでは、デフォルトの認証設定を変更する必要はありません。Don't worry if this all sounds confusing now! Most applications will never need to modify the default authentication configuration.

データベースの検討事項Database Considerations

デフォルトととしてLaravelは、App\User Eloquentモデルappディレクトリに用意しています。このモデルはデフォルトEloquent認証ドライバで使用しています。もしアプリケーションでEloquentを使用しなければ、Laravelクエリビルダを使用するdatabase認証ドライバを使用する必要があります。By default, Laravel includes an App\User Eloquent model[/docs/{{version}}/eloquent] in your app 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 driver which uses the Laravel query builder.

App\Userモデルのデータベーススキマー構築時に、確実にパスワードカラムを最低60文字確保してください。デフォルトの255文字にするのが、良い方法でしょう。When building the database schema for the App\User model, make sure the password column is at least 60 characters in length, the default of 255 would be a good choice.

さらにusers、もしくは同等の働きをするテーブルには、100文字のremember_token文字列カラムも含めてください。このカラムはアプリケーションが管理する"remember me"セッションのトークンを保存しておくカラムです。マイグレーションで$table->rememberToken();を実行すると用意されます。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 "remember me" sessions being maintained by your application. This can be done by using $table->rememberToken(); in a migration.

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

Laravelでは認証に関連する2つのコントローラーがApp\Http\Controllers\Auth名前空間下に用意されています。AuthControllerは新ユーザの登録と「ログイン」を処理します。もうひとつのPasswordControllerには、登録済みユーザがパスワードを忘れた時にリセットするためのロジックが準備されています。必要なメソッドを読み込むために両方のコントローラーでトレイトが使われています。多くのアプリケーションで、これらのコントローラーを変更する必要は全く無いでしょう。Laravel ships with two authentication controllers out of the box, which are located in the App\Http\Controllers\Auth namespace. The AuthController handles new user registration and authentication, while the PasswordController contains the logic to help existing users reset their forgotten passwords. Each of these controllers uses a trait to include their necessary methods. For many applications, you will not need to modify these controllers at all.

ルート定義Routing

簡単なコマンド一つで、認証に必要となるルート定義とビューをすべてスカフォールディングできる簡単な手段をLaravelは提供しています。Laravel provides a quick way to scaffold all of the routes and views you need for authentication using one simple command:

php artisan make:auth

このコマンドはインストールしたてのアプリケーションに対し実行してください。認証の全エンドポイントに対するルートとともに、登録とログインのビューが準備されます。HomeControllerも生成され、アプリケーションのダッシュボード(管理領域)に対する、ログインリクエストのPOSTを処理します。しかし、アプリケーションの必要に応じて、このコントローラは自由に削除できます。This command should be used on fresh applications and will install registration and login views, as well as routes for all authentication end-points. A HomeController will also be generated, which serves post-login requests to your application's dashboard. However, you are free to customize or even remove this controller based on the needs of your application.

ビューViews

前のセクションで説明したとおり、php artisan make:authコマンドはresources/views/authディレクトリへ、認証に必要なすべてのビューを生成します。As mentioned in the previous section, the php artisan make:auth command will create all of the views you need for authentication and place them in the resources/views/auth directory.

make:authコマンドはresources/views/layoutsディレクトリにアプリケーションのベースレイアウトビューも生成します。これらのビューはすべてBootstrap CSSフレームワークを使用していますが、自由にカスタマイズしてください。The make:auth command will also create a resources/views/layouts directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.

認証Authenticating

これで、認証コントローラを含め、必要なルートとビューの準備が整いました。アプリケーションに新しいユーザを登録できるようになりました。ブラウザでアプリケーションへアクセスしてください。認証コントローラは(内部で使用しているトレイトにより)、既存ユーザの認証と、新しいユーザをデータベースへ保存するロジックをすでに備えています。Now that you have routes and views setup for the included authentication controllers, you are ready to register and authenticate new users for your application! You may simply access your application in a browser. The authentication controllers already contain the logic (via their traits) to authenticate existing users and store new users in the database.

パスのカスタマイズPath Customization

ユーザが認証に成功すると、/のURIへリダイレクトします。これをカスタマイズするには、AuthControllerredirectToプロパティに認証後のリダイレクト先の場所を定義してください。When a user is successfully authenticated, they will be redirected to the / URI. You can customize the post-authentication redirect location by defining a redirectTo property on the AuthController:

protected $redirectTo = '/home';

ユーザが認証に失敗した場合、自動的にログインフォームへリダイレクトします。When a user is not successfully authenticated, they will be redirected back to the login form location automatically.

ガードのカスタマイズGuard Customization

更に、ユーザを認証するために使用する「ガード」をカスタマイズすることも可能です。最初に、AuthControllerguardプロパティを定義してください。このプロパティの値は、auth.php設定ファイルのガード設定に対応させます。You may also customize the "guard" that is used to authenticate users. To get started, define a guard property on your AuthController. The value of this property should correspond with one of the guards configured in your auth.php configuration file:

protected $guard = 'admin';

バリデーション/保管域のカスタマイズValidation / Storage Customization

アプリケーションに新しいユーザを登録する場合に入力してもらうフォームのフィールドを変更するか、データベースに新しいユーザレコードを登録する方法をカスタマイズしたい場合は、AuthControllerクラスを変更してください。このクラスはアプリケーションで新しいユーザのバリデーションと作成に責任を持っています。To modify the form fields that are required when a new user registers with your application, or to customize how new user records are inserted into your database, you may modify the AuthController class. This class is responsible for validating and creating new users of your application.

AuthControllervalidatorメソッドはアプリケーションの新しいユーザに対するバリデーションルールで構成されています。このメソッドはお気に召すまま自由に変更してください。The validator method of the AuthController contains the validation rules for new users of the application. You are free to modify this method as you wish.

AuthControllercreateメソッドは新しいApp\UserレコードをEloquent ORMを使用し、データベースに作成することに責任を持っています。データベースの必要に合わせて自由にこのメソッドを変更してください。The create method of the AuthController is responsible for creating new App\User records in your database using the Eloquent ORM[/docs/{{version}}/eloquent]. You are free to modify this method according to the needs of your database.

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

Authファサードを使えば認証済みユーザへ簡単にアクセスできます。You may access the authenticated user via the Auth facade:

$user = Auth::user();

もしくは、ユーザが認証済みであれば、Illuminate\Http\Requestインスタンス経由で、ユーザへアクセスすることもできます。コントローラメソッドでタイプヒントしたクラスは、自動的にインスタンスが依存注入されることを思い出してください。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:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProfileController extends Controller
{
    /**
     * ユーザプロフィールの更新
     *
     * @param  Request  $request
     * @return Response
     */
    public function updateProfile(Request $request)
    {
        if ($request->user()) {
            // $request->user()は認証済みユーザのインスタンスを返す
        }
    }
}

現在のユーザが認証されているか調べるDetermining If The Current User Is Authenticated

ユーザが既にアプリケーションにログインしているかを調べるには、Authファサードのcheckメソッドが使えます。認証時にtrueを返します。To determine if the user is already logged into your application, you may use the check method on the Auth facade, which will return true if the user is authenticated:

if (Auth::check()) {
    // ユーザはログインしている
}

しかし特定のルートやコントローラーにユーザをアクセスさせる前に、認証済みであるかをミドルウェアにより確認することもできます。より詳細についてはルートの保護のドキュメントを参照してください。However, you may use 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にはapp\Http\Middleware\Authenticate.phpの中で定義されているauthミドルウェアが最初から用意されています。ルートの定義にこのミドルウェアを指定するだけです。Route middleware[/docs/{{version}}/middleware] can be used to allow only authenticated users to access a given route. Laravel ships with the auth middleware, which is defined in app\Http\Middleware\Authenticate.php. All you need to do is attach the middleware to a route definition:

// ルートクロージャを使用する

Route::get('profile', ['middleware' => 'auth', function() {
    // 認証済みのユーザのみが入れる
}]);

// コントローラを使用する

Route::get('profile', [
    'middleware' => 'auth',
    'uses' => 'ProfileController@show'
]);

もちろんコントローラークラスを使っているならルート定義に付加する代わりに、コントローラーのコンストラクターでmiddlewareメソッドを呼び出すことができます。Of course, if you are using controller classes[/docs/{{version}}/controllers], you may call the middleware method from the controller's constructor instead of attaching it in the route definition directly:

public function __construct()
{
    $this->middleware('auth');
}

ガードの指定Specifying A Guard

authミドルウェアをルートに対し指定するときに、認証を実行するガードを指定することもできます。When attaching the auth middleware to a route, you may also specify which guard should be used to perform the authentication:

Route::get('profile', [
    'middleware' => 'auth:api',
    'uses' => 'ProfileController@show'
]);

指定するガードは、auth.php設定ファイルのguards配列のキーを指定してください。The guard specified should correspond to one of the keys in the guards array of your auth.php configuration file.

認証回数制限Authentication Throttling

Laravelの組み込みAuthControllerクラスを使用している場合に、アプリケーションのログイン制限を行うにはIlluminate\Foundation\Auth\ThrottlesLoginsトレイトをuseします。デフォルトでは何度も正しくログインできなかった後、一分間ログインできなくなります。制限はユーザの名前/メールアドレスとIPアドレスで限定されます。If you are using Laravel's built-in AuthController class, the Illuminate\Foundation\Auth\ThrottlesLogins trait may be used to throttle login attempts to your application. 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 / e-mail address and their IP address:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    // AuthControllerクラスの残りの部分…
}

自前のユーザ認証Manually Authenticating Users

もちろん、Laravelに含まれる認証コントローラーを使うことを強要しているわけでありません。これらのコントローラーを削除する選択肢を選ぶのなら、Laravel認証クラスを直接使用しユーザの認証を管理する必要があります。心配ありません。それでも簡単です!Of course, you are not required to use the authentication controllers included with Laravel. If you choose to remove these controllers, you will need to manage user authentication using the Laravel authentication classes directly. Don't worry, it's a cinch!

Laravelの認証サービスにはAuthファサードでアクセスできます。クラスの最初でAuthファサードを確実にインポートしておきましょう。次に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:

<?php

namespace App\Http\Controllers;

use Auth;

class AuthController extends Controller
{
    /**
     * 認証を処理する
     *
     * @return Response
     */
    public function authenticate()
    {
        if (Auth::attempt(['email' => $email, 'password' => $password])) {
            // 認証に成功した
            return redirect()->intended('dashboard');
        }
    }
}

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 hashed password value passed to the method via the array. If the two hashed passwords match an authenticated session will be started for the user.

attemptメソッドは、認証が成功すればtrueを返します。失敗時はfalseを返します。The attempt method will return true if authentication was successful. Otherwise, false will be returned.

リダイレクタ―のintendedメソッドは、認証フィルターにかかる前にアクセスしようとしていたURLへ、ユーザをリダイレクトしてくれます。そのリダイレクトが不可能な場合の移動先として、フォールバックURIをこのメソッドに指定できます。The intended method on the redirector will redirect the user to the URL they were attempting to access before being caught by the authentication filter. A fallback URI may be given to this method in case the intended destination is not available.

追加条件の指定Specifying Additional Conditions

お望みであれば、ユーザのメールアドレスとパスワードに付け加え、認証時のクエリに追加の条件を指定することも可能です。If you wish, you also may add extra conditions to the authentication query in addition to the user's e-mail and password. For example, we may verify that user is marked as "active":

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // ユーザは存在しており、かつアクティブで、資格停止されていない
}

注意: この例のように、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.

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

Authファサードのguardメソッドにより、使用したいガードインスタンスを指定できます。これにより全く異なった認証用のモデルやユーザテーブルを使い、アプリケーションの別々の部分に対する認証を管理することができます。You may specify which guard instance you would like to utilize using the guard method on the Auth facade. This allows you to manage authentication for separate parts of your application using entirely separate authenticatable models or user tables.

guardメソッドへ渡すガード名は、auth.php認証ファイルのguards設定の一つと対応している必要があります。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)) {
    //
}

ログアウトLogging Out

アプリケーションからユーザをログアウトさせるには、Authファサードのlogoutメソッドを使用してください。これはユーザセッションの認証情報をクリアします。To log users out of your application, you may use the logout method on the Auth facade. This will clear the authentication information in the user's session:

Auth::logout();

継続ログインRemembering Users

アプリケーションでログイン維持(Remember me)機能を持たせたい場合は、attemptメソッドの第2引数に論理値を指定します。ユーザが自分でログアウトしない限り、認証が無期限に持続するようになります。もちろん、"remember me"トークンを保存するために使用する文字列のremember_tokenカラムをusersテーブルに持たせる必要があります。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, which will keep the user authenticated indefinitely, or until they manually logout. Of course, your users table must include the string remember_token column, which will be used to store the "remember me" token.

if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
    // $rememberがtrueなら、このメンバーは継続ログインされる…
}

この機能を使用している時に、ユーザが"remember me"クッキーを使用して認証されているかを判定するには、viaRememberメソッドを使用します。If you are "remembering" users, you may use the viaRemember method to determine if the user was authenticated using the "remember me" cookie:

if (Auth::viaRemember()) {
    //
}

他の認証方法Other Authentication Methods

Userインスタンスによる認証Authenticate A User Instance

既に存在しているユーザインスタンスでアプリケーションにログインさせる必要があれば、loginメソッドにそのユーザインスタンスを指定し呼び出してください。指定されたオブジェクトはIlluminate\Contracts\Auth\Authenticatable契約を実装している必要があります。もちろん、Laravelが用意しているApp\Userモデルはこのインターフェイスを実装しています。If you need to log an existing user instance into your application, you may call the login method with the user instance. The given object must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract[/docs/{{version}}/contracts]. Of course, the App\User model included with Laravel already implements this interface:

Auth::login($user);

// 指定したユーザでログインする(このセッションだけでない)
Auth::login($user, true);

もちろん、使用したいガードインスタンスを指定することもできます。Of course, you may specify the guard instance you would like to use:

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

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

ユーザをアプリケーションへIDによりログインさせる場合は、loginUsingIdメソッドを使います。このメソッドは認証させたいユーザの主キーだけを引数に受け取ります。To log a user into the application by their ID, you may use the loginUsingId method. This method simply accepts the primary key of the user you wish to authenticate:

Auth::loginUsingId(1);

// 指定したユーザでログインする(このセッションだけでない)
Auth::loginUsingId(1, true);

ユーザを一度だけ認証するAuthenticate A User Once

onceメソッドを使用すると、アプリケーションにユーザをそのリクエストの間だけログインさせることができます。セッションもクッキーも使用しないため、ステートレスなAPIを構築する場合に便利です。onceメソッドの引数はattemptメソッドと同じです。You may use the once method to log a user into the application for a single request. No sessions or cookies will be utilized, which may be helpful when building a stateless API. The once method has the same signature as the attempt method:

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

HTTP基本認証HTTP Basic Authentication

HTTP基本認証により、専用の「ログイン」ページを用意しなくても手っ取り早くアプリケーションにユーザをログインさせられます。これを使用するには、ルートにauth.basicミドルウェアを付けてください。auth.basicミドルウェアはLaravelフレームワークに含まれているので、定義する必要はありません。HTTP Basic Authentication[http://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 your route. The auth.basic middleware is included with the Laravel framework, so you do not need to define it:

Route::get('profile', ['middleware' => 'auth.basic', function() {
    // 認証済みのユーザのみが実行できる…
}]);

ミドルウェアをルートに指定すれば、ブラウザーからこのルートへアクセスされると自動的に認証が求められます。デフォルトでは、auth.basicミドルウェアはユーザを決める"username"としてユーザのemailカラムを使用します。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 use the email column on the user record as the "username".

FastCGIの注意A Note On FastCGI

PHP FastCGIを使用している場合、初期状態のままでHTTP基本認証は正しく動作しないでしょう。以下の行を.htaccessファイルへ追加してください。If you are using PHP FastCGI, HTTP Basic authentication may not work correctly out of the box. The following lines should be added to your .htaccess file:

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

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

セッションの識別クッキーを用いずにHTTP基本認証を使用することもできます。これは特にAPI認証に便利です。実装するには、onceBasicメソッドを呼び出すミドルウェアを定義してください。onceBasicメソッドが何もレスポンスを返さなかった場合、リクエストをアプリケーションの先の処理へ通します。You may also use HTTP Basic Authentication without setting a user identifier cookie in the session, which is particularly useful for API authentication. To do so, 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 Illuminate\Auth\Middleware;

use Auth;
use Closure;

class AuthenticateOnceWithBasicAuth
{
    /**
     * 送信されたリクエストの処理
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $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', ['middleware' => 'auth.basic.once', function() {
    // 認証済みのユーザのみが実行できる
}]);

パスワードリセットResetting Passwords

データベースの検討事項Database Considerations

ほとんどのWebアプリケーションは、パスワードを忘れた場合にリセットする機能をユーザへ提供しています。アプリケーションを構築するたびごと、何度も実装しなくても済むように、Laravelはパスワードリマインダーを送信し、パスワードをリセットするための便利な手法を提供しています。Most web applications provide a way for users to reset their forgotten passwords. Rather than forcing you to re-implement this on each application, Laravel provides convenient methods for sending password reminders and performing password resets.

これを利用するには、App\UserモデルがIlluminate\Contracts\Auth\CanResetPassword契約を実装しているか確認してください。もちろん、フレームワークに用意されているApp\Userモデルでは、既にこのインターフェイスが実装されています。Illuminate\Auth\Passwords\CanResetPasswordトレイトで、このインターフェイスで実装する必要のあるメソッドが定義されています。To get started, verify that your App\User model implements the Illuminate\Contracts\Auth\CanResetPassword contract. Of course, the App\User model included with the framework already implements this interface, and uses the Illuminate\Auth\Passwords\CanResetPassword trait to include the methods needed to implement the interface.

リセットトークンテーブルマイグレーションの生成Generating The Reset Token Table Migration

次にパスワードリセットトークンを保存しておくためのテーブルを作成します。このテーブルのマイグレーションは、最初からLaravelのdatabase/migrationsディレクトリに含まれています。ですから、マイグレートするために必要なのは次のコマンド実行だけです。Next, a table must be created to store the password reset tokens. The migration for this table is included with Laravel out of the box, and resides in the database/migrations directory. So, all you need to do is migrate:

php artisan migrate

ルート定義Routing

Laravelはユーザのパスワードをリセットするために必要なロジックを全部含んでいる、Auth\PasswordControllerを用意しています。パスワードリセットに必要な全ルートは、make:auth Artisanコマンドで生成します。Laravel includes an Auth\PasswordController that contains the logic necessary to reset user passwords. All of the routes needed to perform password resets may be generated using the make:auth Artisan command:

php artisan make:auth

ビューViews

パスワードリセットの場合も、make:authコマンドを実行すれば、パスワードリセットに必要な全部のビューが生成されます。ビューはresources/views/auth/passwordsに生成されます。アプリケーションに合わせ、自由にカスタマイズしてください。Again, Laravel will generate all of the necessary views for password reset when the make:auth command is executed. These views are placed in resources/views/auth/passwords. You are free to customize them as needed for your application.

パスワードリセット後の処理After Resetting Passwords

ユーザのパスワードをリセットするルートとビューを定義できたら、ブラウザーで/password/resetのルートへアクセスするだけです。フレームワークに含まれている PasswordControllerは、パスワードリセットリンクを含むメールを送信し、データベースのパスワードを更新するためのロジックを含んでいます。Once you have defined the routes and views to reset your user's passwords, you may simply access the route in your browser at /password/reset. The PasswordController included with the framework already includes the logic to send the password reset link e-mails as well as update passwords in the database.

パスワードがリセットされたら、そのユーザは自動的にアプリケーションにログインされ、/homeへリダイレクトされます。パスワードリセット後のリダイレクト先をカスタマイズするには、PasswordControllerredirectToプロパティを定義してください。After the password is reset, the user will automatically be logged into the application and redirected to /home. You can customize the post password reset redirect location by defining a redirectTo property on the PasswordController:

protected $redirectTo = '/dashboard';

注意: デフォルトでパスワードリセットトークンは、一時間有効です。これは、config/auth.phpファイルのexpireオプションにより変更できます。Note: By default, password reset tokens expire after one hour. You may change this via the password reset expire option in your config/auth.php file.

カスタマイズCustomization

認証ガードのカスタマイズAuthentication Guard Customization

auth.php設定ファイルにより、複数のユーザテーブルごとに認証の振る舞いを定義するために使用する、「ガード」をそれぞれ設定できます。用意されているPasswordControllerコントローラに$guardプロパティを追加することにより、使用するガードを選択できます。In your auth.php configuration file, you may configure multiple "guards", which may be used to define authentication behavior for multiple user tables. You can customize the included PasswordController to use the guard of your choice by adding a $guard property to the controller:

/**
 * 使用する認証ガード
 *
 * @var string
 */
protected $guard = 'admins';

パスワードブローカーのカスタマイズPassword Broker Customization

複数のユーザテーブルに対するパスワードをリセットするために使用する、別々のパスワード「ブローカー」をauth.phpファイルで設定できます。用意されているPasswordControllerコントローラに$brokerプロパティを追加し、使用するブローカーのカスタマイズができます。In your auth.php configuration file, you may configure multiple password "brokers", which may be used to reset passwords on multiple user tables. You can customize the included PasswordController to use the broker of your choice by adding a $broker property to the controller:

/**
 * 使用するパスワードブローカー
 *
 * @var string
 */
protected $broker = 'admins';

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

独自の認証ガードはAuthファサードのextendメソッドを使用し、定義します。サービスプロバイダの中で、呼び出します。You may define your own authentication guards using the extend method on the Auth facade. You should place this call to provider within a service provider[/docs/{{version}}/providers]:

<?php

namespace App\Providers;

use Auth;
use App\Services\Auth\JwtGuard;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * サービスの初期起動後の登録実行
     *
     * @return void
     */
    public function boot()
    {
        Auth::extend('jwt', function($app, $name, array $config) {
            // Illuminate\Contracts\Auth\Guardのインスタンスを返す

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

    /**
     * コンテナへの結合登録
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

上記の例のように、コールバックをextendメソッドに渡し、Illuminate\Contracts\Auth\Guardの実装を返します。このインスタンスは、カスタムガードで定義が必要ないくつかのメソッドを持っています。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.

カスタムガードが定義できたら、guards設定で使用してください。Once your custom guard has been defined, you may use the guard in your guards configuration:

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

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

ユーザ情報を保管するために伝統的なリレーショナルデータベースを使用したくなければ、Laravelに独自の認証ユーザプロバイダを拡張する必要があります。Authファサードのproviderメソッドを使い、カスタムユーザプロバイダを定義します。 サービスプロバイダの中で、このproviderメソッドを呼び出してください。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. You should place this call to provider within a service provider[/docs/{{version}}/providers]:

<?php

namespace App\Providers;

use Auth;
use App\Extensions\RiakUserProvider;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * サービスの初期起動後の登録実行
     *
     * @return void
     */
    public function boot()
    {
        Auth::provider('riak', function($app, array $config) {
            // Illuminate\Contracts\Auth\UserProviderのインスタンスを返す
            return new RiakUserProvider($app['riak.connection']);
        });
    }

    /**
     * コンテナへの結合登録
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

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

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

次に、このプロバイダをguards設定項目で利用します。Then, you may use this provider in your guards configuration:

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

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

Illuminate\Contracts\Auth\UserProviderは、MySQLやRiakなどのような持続性のストレージシステムに対するIlluminate\Contracts\Auth\Authenticatableの実装を取得することだけに責任を持っています。これらの2つのインターフェイスはユーザデータがどのように保存されているか、それを表すのがどんなタイプのクラスなのかに関わらず、認証メカニズムを機能し続けるために役立っています。The Illuminate\Contracts\Auth\UserProvider implementations are only responsible for fetching a Illuminate\Contracts\Auth\Authenticatable implementation out of a persistent storage system, such as MySQL, Riak, 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 it.

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関数は一意の$identifierremember_tokenフィールドに保存されている"remember me" $tokenからユーザを取得します。前のメソッドと同じく、Authenticatable実装が返されます。The retrieveByToken function retrieves a user by their unique $identifier and "remember me" $token, stored in a field remember_token. As with the previous method, the Authenticatable implementation should be returned.

updateRememberTokenメソッドは$userremember_tokenフィールドを新しい$tokenで更新します。新しいトークンは真新しいものでも、「Remember me」ログインに成功した時の値でも、ログアウト時のnull値でも受け付けます。The updateRememberToken method updates the $user field remember_token with the new $token. The new token can be either a fresh token, assigned on a successful "remember me" login attempt, or a null when the user is logged out.

retrieveByCredentialsメソッドはアプリケーションにログイン時にAuth::attemptメソッドに指定するのと同じく、ユーザ認証情報の配列を引数に取ります。メソッドは認証情報に一致するユーザを裏の持続ストレージから「クエリ」する必要があります。典型的な使用方法の場合、このメソッドは$credentials['username']の"where"条件でクエリを実行するでしょう。メソッドはUserInterfaceの実装を返します。このメソッドはパスワードバリデーションや認証を行ってはいけませんThe retrieveByCredentials method receives the array of credentials passed to the Auth::attempt method when attempting to sign into 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 on $credentials['username']. The method should then return an implementation of UserInterface. This method should not attempt to do any password validation or authentication.

validateCredentialsメソッドは指定された$userとユーザを認証するための$credentialsとを比較します。たとえばこのメソッドは$user->getAuthPassword()文字列と$credentials['password']Hash::makeした値を比較します。このメソッドはユーザの認証情報のバリデーションだけを行い、論理値を返します。The validateCredentials method should compare the given $user with the $credentials to authenticate the user. For example, this method might compare the $user->getAuthPassword() string to a Hash::make of $credentials['password']. This method should only validate the user's credentials and return a boolean.

Authenticatable契約The Authenticatable Contract

これでUserProviderの各メソッドが明らかになりました。続いてAuthenticatable契約を見てみましょう。プロバイダはretrieveByIdretrieveByCredentialsメソッドでこのインターフェイスの実装を返していたことを思い出してください。Now that we have explored each of the methods on the UserProvider, let's take a look at the Authenticatable contract. Remember, the provider should return implementations of this interface from the retrieveById 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はユーザのハッシュ済みのパスワードを返します。このインターフェイスはどのORMや抽象ストレージ層を使用しているかに関わらず、どんなUserクラスに対しても認証システムが動作するようにしてくれています。デフォルトでLaravelはappディレクトリ中に、このインターフェイスを実装してるUserクラスを持っています。ですから実装例として、このクラスを調べてみてください。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. In a MySQL back-end, again, this would be the auto-incrementing primary key. The getAuthPassword should return the user's hashed password. 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 User class in the app directory which implements this interface, so you may consult this class for an implementation example.

イベントEvents

Laravelは認証処理の過程で、様々なイベントを発行します。EventServiceProviderの中で、こうしたイベントに対するリスナを設定できます。:Laravel raises 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\Attempting' => [
        'App\Listeners\LogAuthenticationAttempt',
    ],

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

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

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

章選択

設定

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

ヘッダー項目移動

キーボード操作