イントロダクション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.
データベースの検討事項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
モデルのデータベーススキーマを構築する場合は、passwordカラムを最低60文字確実に確保してください。When building the database schema
for the App\User
model, make sure the
password column is at least 60 characters in
length.
さらに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
認証コントローラーへリクエストを送るルートはデフォルトで含まれていません。app/Http/routes.php
へ自分で以下の定義を追加してください。By default, no
routes[/docs/{{version}}/routing] are
included to point requests to the authentication
controllers. You may manually add them to your
app/Http/routes.php
file:
// 認証のルート定義…
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');
// 登録のルート定義…
Route::get('auth/register', 'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');
ビューViews
認証のコントローラーはフレームワークに含まれていますが、これらのコントローラーがレンダーするビューは用意する必要があります。ビューはresources/views/auth
に設置します。これらのビューはお好きなようにカスタマイズしてください。ロジックのビューはresources/views/auth/login.blade.php
へ、登録のビューはresources/views/auth/register.blade.php
へ設置してください。Though the authentication
controllers are included with the framework, you
will need to provide
views[/docs/{{version}}/views] that these
controllers can render. The views should be placed
in the resources/views/auth
directory.
You are free to customize these views however you
wish. The login view should be placed at
resources/views/auth/login.blade.php
,
and the registration view should be placed at
resources/views/auth/register.blade.php
.
サンプル認証フォームSample Authentication Form
<!-- resources/views/auth/login.blade.php -->
<form method="POST" action="/auth/login">
{!! csrf_field() !!}
<div>
メールアドレス
<input type="email" name="email" value="{{ old('email') }}">
</div>
<div>
パスワード
<input type="password" name="password" id="password">
</div>
<div>
<input type="checkbox" name="remember"> ログインを継続する
</div>
<div>
<button type="submit">ログイン</button>
</div>
</form>
サンプル登録フォームSample Registration Form
<!-- resources/views/auth/register.blade.php -->
<form method="POST" action="/auth/register">
{!! csrf_field() !!}
<div>
ユーザー名
<input type="text" name="name" value="{{ old('name') }}">
</div>
<div>
メールアドレス
<input type="email" name="email" value="{{ old('email') }}">
</div>
<div>
パスワード
<input type="password" name="password">
</div>
<div>
パスワード確認
<input type="password" name="password_confirmation">
</div>
<div>
<button type="submit">登録</button>
</div>
</form>
認証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 defined routes in a browser. The authentication controllers already contain the logic (via their traits) to authenticate existing users and store new users in the database.
ユーザーが認証されるとデフォルトで/home
URIへリダイレクトされますが、このルートを変更する必要があるでしょう。認証後のリダイレクト場所はAuthController
のredirectPath
プロパティを定義することでカスタマイズできます。When a user is successfully
authenticated, they will be redirected to the
/home
URI, which you will need to
register a route to handle. You can customize the
post-authentication redirect location by defining a
redirectPath
property on the
AuthController
:
protected $redirectPath = '/dashboard';
ユーザーが認証されていないと/auth/login
URIへリダイレクトされます。認証されていない時のリダイレクト先はAuthController
のloginPath
プロパティでデフォルトを指定できます。When a user is not successfully
authenticated, they will be redirected to the
/auth/login
URI. You can customize the
failed post-authentication redirect location by
defining a loginPath
property on the
AuthController
:
protected $loginPath = '/login';
ユーザーが保護されているルートへアクセスしようとし、送り返される先をloginPath
は変更しません。App\Http\Middleware\Authenticate
ミドルウェアのhandle
メソッドにより制御されています。The loginPath
will
not change where a user is bounced if they try to
access a protected route. That is controlled by the
App\Http\Middleware\Authenticate
middleware's handle
method.
カスタマイズCustomizations
アプリケーションに新しいユーザーを登録する場合に入力してもらうフォームのフィールドを変更するか、データベースに新しいユーザーレコードの登録方法をカスタマイズしたい場合は、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.
AuthController
のvalidator
メソッドはアプリケーションの新しいユーザーに対するバリデーションルールで構成されています。このメソッドはお気に召すまま自由に変更してください。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.
AuthController
のcreate
メソッドは新しい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:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
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');
}
認証制限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;
// 後略…
}
自前のユーザー認証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;
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
メソッドは最初の引数として、キー/値ペアの配列を受け取ります。配列中の他の値は、データベーステーブルの中からそのユーザーを見つけるために使用されます。ですから、上の例では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.
お望みであれば、ユーザーのメールアドレスとパスワードに付け加え、認証時のクエリーに追加の条件を指定することも可能です。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])) {
// ユーザーは存在し、アクティブで、利用停止されていない
}
アプリケーションからユーザーをログアウトさせるには、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);
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);
ユーザーを一度だけ認証する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
はユーザーパスワードをリセットするために必要なロジックを持っています。しかし、このコントローラーに対するルートは定義する必要があります。Laravel includes an
Auth\PasswordController
that contains
the logic necessary to reset user passwords.
However, you will need to define routes to point
requests to this controller:
// パスワードリセットリンクを要求するルート…
Route::get('password/email', 'Auth\PasswordController@getEmail');
Route::post('password/email', 'Auth\PasswordController@postEmail');
// パスワードリセットルート
Route::get('password/reset/{token}', 'Auth\PasswordController@getReset');
Route::post('password/reset', 'Auth\PasswordController@postReset');
ビューViews
PasswordController
へのルート定義に加え、このコントローラーにより返されるビューを準備する必要もあります。心配ありません。取り掛かりやすいようにサンプルビューを提供します。もちろん、お好きなようにフォームを変更してください。In addition to defining the
routes for the PasswordController
, you
will need to provide views that can be returned by
this controller. Don't worry, we will provide sample
views to help you get started. Of course, you are
free to style your forms however you
wish.
パスワードリセットリンクのリクエストサンプルフォームSample Password Reset Link Request Form
パスワードリセットフォームのためにHTMLビューを用意する必要があります。このビューはresources/views/auth/password.blade.php
として設置します。このフォームは、パスワードのリセットリンクを受け付けるため、ユーザーのメールアドレスを指定するフィールドを一つ持っています。You will need to provide an HTML
view for the password reset request form. This view
should be placed at
resources/views/auth/password.blade.php
.
This form provides a single field for the user's
e-mail address, allowing them to request a password
reset link:
<!-- resources/views/auth/password.blade.php -->
<form method="POST" action="/password/email">
{!! csrf_field() !!}
@if (count($errors) > 0)
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
<div>
Email
<input type="email" name="email" value="{{ old('email') }}">
</div>
<div>
<button type="submit">
パスワードリセットリンクの送信
</button>
</div>
</form>
ユーザーがパスワードのリセットをリクエストすると、PasswordController
のgetReset
メソッドへのリンクを含んだメールを受け取ることになります。通常、ルートは/password/reset
です。このメールのビューはresources/views/emails/password.blade.php
です。このビューは、パスワードのリセットを要求したユーザーであるかどうかを確認するための、パスワードリセットトークンを持つ$token変数を受け取ります。取り掛かりやすいでしょうから、メールのサンプルもどうぞ。When a user submits a request to
reset their password, they will receive an e-mail
with a link that points to the getReset
method (typically routed at
/password/reset
) of the
PasswordController
. You will need to
create a view for this e-mail at
resources/views/emails/password.blade.php
.
The view will receive the $token
variable which contains the password reset token to
match the user to the password reset request. Here
is an example e-mail view to get you
started:
<!-- resources/views/emails/password.blade.php -->
パスワードをリセットするためにリンクをクリックしてください。 {{ url('password/reset/'.$token) }}
パスワードリセットサンプルフォームSample Password Reset Form
ユーザーがパスワードをリセットするためにメールの中のリンクをクリックすると、パスワードリセットフォームが表示されます。このビューはresources/views/auth/reset.blade.php
へ用意してください。When the user clicks the e-mailed
link to reset their password, they will be presented
with a password reset form. This view should be
placed at
resources/views/auth/reset.blade.php
.
サンプルパスワードフォームをどうぞ。Here is a sample password reset form to get you started:
<!-- resources/views/auth/reset.blade.php -->
<form method="POST" action="/password/reset">
{!! csrf_field() !!}
<input type="hidden" name="token" value="{{ $token }}">
@if (count($errors) > 0)
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
<div>
メールアドレス
<input type="email" name="email" value="{{ old('email') }}">
</div>
<div>
パスワード
<input type="password" name="password">
</div>
<div>
パスワード確認
<input type="password" name="password_confirmation">
</div>
<div>
<button type="submit">
パスワードリセット
</button>
</div>
</form>
パスワードリセット後の処理After Resetting Passwords
ユーザーのパスワードリセットのためにルートとビューを定義したら、あとはブラウザでアクセスしてもらうだけです。フレームワークが用意しているPasswordController
にはパスワードリセットリンクのメール送信し、データベースのパスワードを更新するロジックが用意されています。Once you have defined the routes
and views to reset your user's passwords, you may
simply access the routes in your browser. 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
へリダイレクトされます。パスワードリセット後のリダイレクト先をカスタマイズするには、PasswordController
のredirectTo
プロパティを定義してください。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';
注意: パスワードリセットトークンの有効時間はデフォルトで1時間です。
config/auth.php
ファイルの中のreminder.expire
オプションで変更できます。Note: By default, password reset tokens expire after one hour. You may change this via thereminder.expire
option in yourconfig/auth.php
file.
ソーシャル認証Social Authentication
典型的なフォームを元にした認証に加え、LaravelはLaravel Socialite(ソシエリート:名士)による、OAuthプロバイダーを利用した簡単で便利な認証方法も提供します。Socialiteは現在、Facebook、Twitter、LinkedIn、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, LinkedIn, Google, GitHub and Bitbucket.
Socialiteを使用する場合、composer.json
にパッケージを追加してください。To get started with Socialite,
add to your composer.json
file as a
dependency:
composer require laravel/socialite
設定Configuration
Socialiteライブラリをインストールしたら、config/app.php
設定ファイルにLaravel\Socialite\SocialiteServiceProvider
を登録してください。After installing the Socialite
library, register the
Laravel\Socialite\SocialiteServiceProvider
in your config/app.php
configuration
file:
'providers' => [
// 他のサービスプロバイダー
Laravel\Socialite\SocialiteServiceProvider::class,
],
さらに、app
設定ファイルのaliases
配列に、Socialite
ファサードを追加してください。Also, add the
Socialite
facade to the
aliases
array in your app
configuration file:
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
続いてアプリケーションで使用するOAuthサービスの認証情報を追加する必要があります。認証情報はconfig/services.php
設定ファイルで指定します。アプリケーションに必要なプロバイダーによりfacebook
、twitter
、linkedin
、google
、github
、bitbucket
のキーを設定してください。You will also 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
, linkedin
,
google
, github
or
bitbucket
, depending on the providers
your application requires. For example:
'github' => [
'client_id' => 'あなたの-github-app-id',
'client_secret' => 'あなたの-github-app-secret',
'redirect' => 'http://あなたの-callback-url',
],
基本的な使用法Basic Usage
これでユーザーを認証する準備ができました!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. We will access Socialite using
the Socialite
facade[/docs/{{version}}/facades]:
<?php
namespace App\Http\Controllers;
use Socialite;
use Illuminate\Routing\Controller;
class AuthController extends Controller
{
/**
* ユーザーをGitHubの認証ページヘリダイレクト
*
* @return Response
*/
public function redirectToProvider()
{
return Socialite::driver('github')->redirect();
}
/**
* ユーザーの情報をGitHubから取得
*
* @return Response
*/
public function handleProviderCallback()
{
$user = Socialite::driver('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 using the scope
method. This
method will overwrite all existing
scopes:
return Socialite::driver('github')
->scopes(['scope1', 'scope2'])->redirect();
当然ながらコントローラーメソッドへのルートを定義する必要があります。Of course, you will need to define routes to your controller methods:
Route::get('auth/github', 'Auth\AuthController@redirectToProvider');
Route::get('auth/github/callback', 'Auth\AuthController@handleProviderCallback');
多くのOAuthプロバイダーはリダイレクトリクエストでオプションのパラメーターをサポートしています。リクエストにオプションのパラメーターを含めるには連想配列をwith
メソッドに渡し、呼び出してください。A number of OAuth providers
support optional parameters in the redirect request.
To include any optional parameters in the request,
call the with
method with an
associative array:
return Socialite::driver('google')
->with(['hd' => 'example.com'])->redirect();
ユーザーの詳細の取得Retrieving User Details
ユーザーのインスタンスを取得したら、そのユーザーに関する詳細情報をさらに得られます。Once you have a user instance, you can grab a few more details about the user:
$user = Socialite::driver('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();
カスタム認証ドライバーの追加Adding Custom Authentication Drivers
ユーザーを保存するために伝統的なリレーショナル・データベースを使用していないのなら、自分の認証ドライバー作成するためにLaravelを拡張する必要があります。Auth
ファサードのextends
メソッドで、カスタムドライバーを定義できます。通常extends
は、サービスプロバイダーの中で呼び出します。If you are not using a
traditional relational database to store your users,
you will need to extend Laravel with your own
authentication driver. We will use the
extend
method on the Auth
facade to define a custom driver. You should place
this call to extend
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::extend('riak', function($app) {
// Illuminate\Contracts\Auth\UserProviderのインスタンスを返す…
return new RiakUserProvider($app['riak.connection']);
});
}
/**
* コンテナに結合を登録
*
* @return void
*/
public function register()
{
//
}
}
extend
メソッドでドライバーを登録したら、config.auth.php
設定ファイルで新しいドライバーに切り替えます。After you have registered the
driver with the extend
method, you may
switch to the new driver in your
config/auth.php
configuration
file.
Userプロバイダー契約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
関数は一意の$identifier
とremember_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
メソッドは$user
のremember_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.
認証契約The Authenticatable Contract
これでUserProvider
の各メソッドが明らかになりました。続いてAuthenticatable
契約を見てみましょう。プロバイダーはretrieveById
とretrieveByCredentials
メソッドでこのインターフェイスの実装を返していたことを思い出してください。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 getAuthIdentifier();
public function getAuthPassword();
public function getRememberToken();
public function setRememberToken($value);
public function getRememberTokenName();
}
このインターフェイスはシンプルです。getAuthIdentifier
メソッドはユーザーの主キーを返します。MySQLを裏で使用している場合、これは自動増分される主キーでしょう。getAuthPassword
はユーザーのハッシュ済みのパスワードを返します。このインターフェイスはどのORMや抽象ストレージ層を使用しているかに関わらず、どんなUserクラスに対しても認証システムが動作するようにしてくれています。デフォルトでLaravelは、このインターフェイスを実装してるapp
ディレクトリーの中のUser
クラスを持っています。ですから実装例としてこのクラスを調べてみてください。This interface is simple. 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
:
/**
* アプリケーションに対するその他のイベントの登録
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
// 認証が試まれるたびに発行される
$events->listen('auth.attempt', function ($credentials, $remember, $login) {
//
});
// ログインに成功した時に発行される
$events->listen('auth.login', function ($user, $remember) {
//
});
// ログアウト時に発行される
$events->listen('auth.logout', function ($user) {
//
});
}