Readouble

Laravel 5.0 認証

イントロダクション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はデフォルトとして、appディレクトリーの中の、App/Userモデルを読み込みます。このモデルはデフォルトのEloquent認証ドライバーと共に使用されます。By default, Laravel includes an App\User model in your app directory. This model may be used with the default Eloquent authentication driver.

重要: このモデルのデータベーススキーマを定義するとき、パスワード(password)カラムは最低でも60文字にしてください。また使用する前に、空文字列を許し(NULLABLE)100文字の文字列のremember_tokenカラムをusers(もしくは同様の)テーブルへ確実に定義してください。マイグレーション中に$table->rememberToken();を使い定義すれば、このカラムが設定されます。もちろん、Laravel5には、これらのカラムのためのマイグレーションを最初から用意してあります!Remember: when building the database schema for this model, make the password column at least 60 characters. Also, before getting started, make sure 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. Of course, Laravel 5 ships migrations for these columns out of the box!

アプリケーションでEloquentを使用しない場合は、Laravelクエリービルダーを使用する、databaseドライバーを使用してください。If your application is not using Eloquent, you may use the database authentication driver which uses the Laravel query builder.

ユーザー認証Authenticating Users

Laravelでは認証に関連する2つのコントローラーが用意されています。AuthControllerは、新ユーザーの登録と、「ログイン」を処理します。もうひとつのPasswordControllerには、登録済みユーザーがパスワードを忘れた時にリセットするためのロジックが準備されています。Laravel ships with two authentication related controllers out of the box. The AuthController handles new user registration and "logging in", while the PasswordController contains the logic to help existing users reset their forgotten passwords.

必要なメソッドを読み込むために、両方のコントローラーでトレイトが使われています。多くのアプリケーションで、これらのコントローラーを変更する必要は全く無いでしょう。これらのコントローラーが表示するビューは、resources/views/authディレクトリーにあります。こちらはお望み通り、自由に変更してください。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. The views that these controllers render are located in the resources/views/auth directory. You are free to customize these views however you wish.

ユーザ登録The User Registrar

アプリケーションに新しいユーザーを登録するときに利用する、フォームのフィールドを変更するためには、App\Services\Registrarクラスを変更してください。このクラスは、バリデーションとアプリケーションの新ユーザーを作成することに責任を持っています。To modify the form fields that are required when a new user registers with your application, you may modify the App\Services\Registrar class. This class is responsible for validating and creating new users of your application.

Registrarvalidatorメソッドは、アプリケーションの新ユーザーに対する、バリデーションルールで構成されています。一方で、Registrarcreateメソッドは、データベースに新しいUserレコードを作成することに責任を持っています。両メソッドとも、お好きなように変更してかまいません。RegistrarAuthControllerにより、AuthenticatesAndRegistersUsersトレイトの中のメソッドを通じて呼びだされます。The validator method of the Registrar contains the validation rules for new users of the application, while the create method of the Registrar is responsible for creating new User records in your database. You are free to modify each of these methods as you wish. The Registrar is called by the AuthController via the methods contained in the AuthenticatesAndRegistersUsers trait.

手動認証Manual Authentication

提供しているAuthController実装を使用しない選択をする場合は、Laravel認証クラスを直接使用し、ユーザーの認証を管理する必要があります。心配ありません。それでも、簡単ですよ!attemptメソッドを最初に見てみましょう。If you choose not to use the provided AuthController implementation, you will need to manage the authentication of your users using the Laravel authentication classes directly. Don't worry, it's still a cinch! First, let's check out the attempt method:

<?php namespace App\Http\Controllers;

use Auth;
use Illuminate\Routing\Controller;

class AuthController extends Controller {

	/**
	 * 認証の確認作業を処理する
	 *
	 * @return Response
	 */
	public function authenticate()
	{
		if (Auth::attempt(['email' => $email, 'password' => $password]))
		{
			return redirect()->intended('dashboard');
		}
	}

}

attemptメソッドは最初の引数として、キー/値ペアの配列を受け取ります。password値はハッシュされている必要があります。配列中の他の値は、データベーステーブルの中から、そのユーザーを見つけるために使用されます。ですから、上の例ではemailカラムの値により、ユーザーが取得されます。ユーザーが見つかれば、配列でメソッドに渡されたハッシュ済みのpassword値と、データベースに保存してあったハッシュ済みpasswordが比較されます。2つのハッシュ済みパスワードが一致したら、そのユーザーの新しい認証セッションが開始されます。The attempt method accepts an array of key / value pairs as its first argument. The password value will be hashed[/docs/{{version}}/hashing]. The other 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, a new 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.

注意: この例のように、emailを必ず認証に使用しなくてならない訳ではありません。データーベース中にある、ユーザー名(username)に該当する一意のカラムであれば、何でも使用できます。Note: In this example, 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.

intendedリダイレクトメソッドは、認証フィルターにかかる前に、アクセスしようとしていたURLへ、ユーザーをリダイレクトしてくれます。そのリダイレクトが不可能な場合の移動先として、フォールバックURIをこのメソッドに指定できます。The intended redirect function 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.

条件付きユーザー認証Authenticating A User With Conditions

認証時のクエリーに、追加の条件を指定することも可能です。You also may add extra conditions to the authentication query:

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1]))
{
	// ユーザーは存在し、アクティブになっている
}

ユーザー認証済みの判定Determining If A User Is Authenticated

ユーザーがアプリケーションにログインしているかを判断するには、checkメソッドを使用してください。To determine if the user is already logged into your application, you may use the check method:

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

ユーザー認証とログインの持続Authenticating A User And "Remembering" Them

アプリケーションでログイン維持(Remember me)機能を持たせたい場合は、attemptメソッドの第2引数に論理値でtrueを指定します。ユーザーが自分でログアウトしない限り、認証が持続するようになります。もちろん、"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())
{
	//
}

IDによるユーザー認証Authenticating Users By ID

ユーザーをアプリケーションへ、IDによりログインさせる場合は、loginUsingIdメソッドを使います。To log a user into the application by their ID, use the loginUsingId method:

Auth::loginUsingId(1);

ログインさせずに認証データー確認Validating User Credentials Without Login

アプリケーションにユーザーを実際にログインさせずに、認証データーを確認だけしたい場合は、validateメソッドを使用してください。The validate method allows you to validate a user's credentials without actually logging them into the application:

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

リクエスト1回のみのユーザーログインLogging A User In For A Single Request

onceメソッドを使用すると、アプリケーションにユーザーをそのリクエストの間だけログインさせることができます。セッションもクッキーも使用されません。You may also use the once method to log a user into the application for a single request. No sessions or cookies will be utilized:

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

ユーザーの手動ログインManually Logging In A User

アプリケーションに、既に存在するユーザーインスタンスを用いてログインさせる必要がある場合、loginメソッドへ渡し、呼び出してください。If you need to log an existing user instance into your application, you may call the login method with the user instance:

Auth::login($user);

これは認証データーを使用し、attemptメソッドでログインした場合と同じように動作します。This is equivalent to logging in a user via credentials using the attempt method.

アプリケーションからのログアウトLogging A User Out Of The Application

Auth::logout();

もちろん、組み込み済みのLaravel認証コントローラーを使用しているのでしたら、ユーザーをアプリケーションからログアウトさせるためのコントローラーメソッドは、最初から用意してあります。Of course, if you are using the built-in Laravel authentication controllers, a controller method that handles logging users out of the application is provided out of the box.

認証イベントAuthentication Events

attemptメソッドが呼び出されると、auth.attemptイベントが発行されます。認証が成功し、ユーザーがログインすると、auth.loginイベントが同様に発行されます。When the attempt method is called, the auth.attempt event[/docs/{{version}}/events] will be fired. If the authentication attempt is successful and the user is logged in, the auth.login event will be fired as well.

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

一度ユーザーが認証されると、そのユーザーのインスタンスを取得する様々な方法が利用できます。Once a user is authenticated, there are several ways to obtain an instance of the User.

最初に、Authファサードによりユーザーにアクセスしてみましょう。First, you may access the user from the Auth facade:

<?php namespace App\Http\Controllers;

use Auth;
use Illuminate\Routing\Controller;

class ProfileController extends Controller {

	/**
	 * ユーザープロファイルの更新
	 *
	 * @return Response
	 */
	public function updateProfile()
	{
		if (Auth::user())
		{
			// Auth::user()で認証済みユーザーのインスタンスが返される…
		}
	}

}

2つ目に、Illuminate\Http\Requestを利用して、認証済みユーザーへアクセスしてみましょう。Second, you may access the authenticated user via an Illuminate\Http\Request instance:

<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class ProfileController extends Controller {

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

}

3つ目は、Illuminate\Contracts\Auth\Authenticatable契約のタイプヒントを使用します。このタイプヒントはコントローラーのコンストラクターかコントローラーメソッド、もしくはサービスコンテナにより依存解決されるクラスのコンストラクターで指定します。Thirdly, you may type-hint the Illuminate\Contracts\Auth\Authenticatable contract. This type-hint may be added to a controller constructor, controller method, or any other constructor of a class resolved by the service container[/docs/{{version}}/container]:

<?php namespace App\Http\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\Contracts\Auth\Authenticatable;

class ProfileController extends Controller {

	/**
	 * ユーザープロファイルの更新
	 *
	 * @return Response
	 */
	public function updateProfile(Authenticatable $user)
	{
		// $userは認証済みユーザーのインスタンス
	}

}

ルート保護Protecting Routes

ルートミドルウェアにより、認証済みユーザーだけが指定したルートへのアクセスを行えるようにできます。Laravelはデフォルトで、authミドルウェアを提供しており、app\Http\Middleware\Authenticate.phpの中で定義されています。皆さんが必要なのは、これをルート定義で指定することだけです。Route middleware[/docs/{{version}}/middleware] can be used to allow only authenticated users to access a given route. Laravel provides the auth middleware by default, and it is defined in app\Http\Middleware\Authenticate.php. All you need to do is attach it to a route definition:

// ルートクロージャー使用の場合

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

// コントローラー使用の場合

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

HTTP基本認証HTTP Basic Authentication

HTTP基本認証により、専用の「ログイン」ページを用意しなくても、素早くアプリケーションにユーザーをログインさせられます。これを使用するには、ルートにauth.basicミドルウェアを付けてください。HTTP Basic 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 to your route:

HTTP基本認証によるルート保護Protecting A Route With HTTP Basic

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

basicフィルターはユーザー識別に、レコードのemailカラムをデフォルトで使用します。By default, the basic middleware will use the email column on the user record as the "username".

ステートレスなHTTP基本フィルターSetting Up A Stateless HTTP Basic Filter

セッションの識別クッキーを用いずに、HTTP基本認証を使用することもできます。これは特にAPI認証に便利です。実装するには、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:

public function handle($request, Closure $next)
{
	return Auth::onceBasic() ?: $next($request);
}

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}]

パスワードリマインダーとリセットPassword Reminders & Reset

モデルとテーブルModel & Table

ほとんどの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.

これを利用するには、UserモデルがIlluminate\Contracts\Auth\CanResetPassword契約を実装しているか確認してください。もちろん、フレームワークに用意されているUserモデルでは、既にこのインターフェイスが実装されています。Illuminate\Auth\Passwords\CanResetPasswordトレイトで、このインターフェイスで実装する必要のあるメソッドが定義されています。To get started, verify that your User model implements the Illuminate\Contracts\Auth\CanResetPassword contract. Of course, the 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 Reminder 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

パスワードリマインダーコントローラーPassword Reminder Controller

Laravelには、ユーザーのパスワードをリセットするために必要なロジックで構成されたAuth\PasswordControllerも備わっています。簡単に初められるように、ビューも用意しています!ビューはresources/views/authディレクトリーにあります。アプリケーションのデザインに合わせ、思いのまま自由に変更してください。Laravel also includes an Auth\PasswordController that contains the logic necessary to reset user passwords. We've even provided views to get you started! The views are located in the resources/views/auth directory. You are free to modify these views as you wish to suit your own application's design.

PasswordControllergetResetメソッドへ張ったリンクをクリックすると、ユーザーはメールを受信することになります。このメソッドはパスワードリセットフォームを表示し、ユーザーがパスワードをリセットできるようにします。パスワードがリセットされると、そのユーザーは自動的にアプリケーションにログインされ、/homeへリダイレクトされます。リセット後のリダイレクト先をカスタマイズするには、PasswordControllerredirectToプロパティを定義してください。Your user will receive an e-mail with a link that points to the getReset method of the PasswordController. This method will render the password reset form and allow users to reset their passwords. After the password is reset, the user will automatically be logged into the application and redirected to /home. You can customize the post-reset redirect location by defining a redirectTo property on the PasswordController:

protected $redirectTo = '/dashboard';

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

ソーシャル認証Social Authentication

典型的なフォームを元にした認証に加え、LaravelはLaravel Socialite(ソシエリート:名士)による、OAuthプロバイダーを利用した簡単で便利な認証方法も提供します。Socialiteは現在、Facebook、Twitter、Google、GitHub、Bitbucketをサポートしています。In addition to typical, form based authentication, Laravel also provides a simple, convenient way to authenticate with OAuth providers using Laravel Socialite[https://github.com/laravel/socialite]. Socialite currently supports authentication with Facebook, Twitter, Google, GitHub and Bitbucket.

Socialiteを使用する場合、composer.jsonにパッケージを追加してください。To get started with Socialite, include the package in your composer.json file:

"laravel/socialite": "~2.0"

次に、config/app.php設定ファイルで、Laravel\Socialite\SocialiteServiceProviderを登録します。ファサードを追加するのもよいでしょう。Next, register the Laravel\Socialite\SocialiteServiceProvider in your config/app.php configuration file. You may also register a facade[/docs/{{version}}/facades]:

'Socialize' => 'Laravel\Socialite\Facades\Socialite',

続いてアプリケーションで使用するOAuthサービスの認証情報を追加する必要があります。認証情報は、config/services.php設定ファイルで指定します。アプリケーションに必要なプロバイダーにより、facebooktwittergooglegithubのキーを設定してください。You will need to add credentials for the OAuth services your application utilizes. These credentials should be placed in your config/services.php configuration file, and should use the key facebook, twitter, google, or github, depending on the providers your application requires. For example:

'github' => [
	'client_id' => 'your-github-app-id',
	'client_secret' => 'your-github-app-secret',
	'redirect' => 'http://your-callback-url',
],

これでユーザーを認証する準備ができました!2つのルートを定義する必要があります。一つはOAuthプロバイダーへユーザーをリダイレクトするルート、もう一つは認証後に、プロバイダーからのコールバックを受け取るルートです。以下の例では、Socializeファサードを使用しています。Next, you are ready to authenticate users! You will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication. Here's an example using the Socialize facade:

public function redirectToProvider()
{
	return Socialize::with('github')->redirect();
}

public function handleProviderCallback()
{
	$user = Socialize::with('github')->user();

	// $user->token;
}

redirectメソッドは、ユーザーをOAuthプロバイダーへ送る面倒を見ます。一方のuserメソッドはリクエストを読み、プロバーダーからのユーザー情報を取得します。ユーザーをリダイレクトする前に、そのリクエストに"scopes"を指定することもできます。The redirect method takes care of sending the user to the OAuth provider, while the user method will read the incoming request and retrieve the user's information from the provider. Before redirecting the user, you may also set "scopes" on the request:

return Socialize::with('github')->scopes(['scope1', 'scope2'])->redirect();

ユーザーのインスタンスを取得したら、そのユーザーに関する詳細情報をさらに得られます。Once you have a user instance, you can grab a few more details about the user:

ユーザーの詳細情報取得Retrieving User Details

$user = Socialize::with('github')->user();

// OAuth Two プロバイダー
$token = $user->token;

// OAuth One プロバイダー
$token = $user->token;
$tokenSecret = $user->tokenSecret;

// 全プロバイダー
$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();

章選択

Artisan CLI

設定

明暗テーマ
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!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作