設定Configuration
Laravelは認証をとてもシンプルに実現する目的を持っています。実際、最初から全てが設定済みです。認証の設定ファイルはapp/config/auth.php
で、認証機能の動作を調整するため、読みやすいコメントをつけた多くのオプションで構成されています。Laravel aims to make implementing
authentication very simple. In fact, almost
everything is configured for you out of the box. The
authentication configuration file is located at
app/config/auth.php
, which contains
several well documented options for tweaking the
behavior of the authentication
facilities.
LaravelはEloquent認証ドライバーでデフォルトとして使用されるUser
モデルをapp/models
ディレクトリーに用意してあります。このモデルのスキーマを作成する場合、パスワードフィールドは最低60文字必要であることを覚えておいてください。By default, Laravel includes a
User
model in your
app/models
directory which may be used
with the default Eloquent authentication driver.
Please remember when building the Schema for this
Model to ensure that the password field is a minimum
of 60 characters.
もし、アプリケーションでEloquentを使用しないのであれば、database
認証ドライバーでクエリービルダーを使ってください。If your application is not using
Eloquent, you may use the database
authentication driver which uses the Laravel query
builder.
注目: 認証を使い始める前に、
users
(もしくは同様の)テーブルにNULLを許す、100文字のremember_token
カラムを確実に用意してください。このカラムはアプリケーションで"Remember me"(持続的)セッションのトークンを保存するために使用されます。マイグレーション時に、$table->rememberToken();
を使用すれば作成されます。Note: Before getting started, make sure that yourusers
(or equivalent) table contains a nullable, stringremember_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.
パスワードの保存Storing Passwords
LaravelのHash
クラスは安全なBcryptハッシュを提供しています。The Laravel Hash
class provides secure Bcrypt hashing:
Bcryptを使いパスワードをハッシュするHashing A Password Using Bcrypt
$password = Hash::make('secret');
ハッシュに対し、パスワードを確認するVerifying A Password Against A Hash
if (Hash::check('secret', $hashedPassword))
{
// パスワード一致...
}
パスワードに再ハッシュが必要かチェックするChecking If A Password Needs To Be Rehashed
if (Hash::needsRehash($hashed))
{
$hashed = Hash::make('secret');
}
ユーザー認証Authenticating Users
あるユーザーをアプリケーションにログインさせる場合は、Auth::attempt
メソッドを使います。To log a user into your
application, you may use the
Auth::attempt
method.
if (Auth::attempt(array('email' => $email, 'password' => $password)))
{
return Redirect::intended('dashboard');
}
email
が必須のオプションでないことに注意してください。主に例を示すために使っているだけです。データベースの中にあるどんなカラム名でも"username"に該当するものを使用できます。
Redirect::intended
関数は認証フィルターでキャッチされる前にアクセスしてきた、前のURLへユーザーをリダイレクトさせます。このメソッドにはフォールバックURIを指定機で、リダイレクト先へ転送できない場合に利用されます。Take note that email
is not a required option, it is merely used for
example. You should use whatever column name
corresponds to a "username" in your
database. The Redirect::intended
function will redirect the user to the URL they were
trying 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.
attempt
メソッドが呼び出された時にauth.attempt
イベントが発行されます。同様に、認証に成功した場合はauth.login
イベントが発行されます。When the attempt
method is called, the auth.attempt
event[/docs/4.2/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.
ユーザーが認証されているか判定する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
を渡す必要があります。それにより無期限に(もしくは手動でログアウトされるまで)認証が維持されます。もちろんusers
テーブルに、"Remember
me"トークンを保存するために使用する、文字列のremember_token
カラムを用意しておく必要があります。If you would like to provide
"remember me" functionality in your
application, you may pass true
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(array('email' => $email, 'password' => $password), true))
{
// このユーザーは覚えられた...
}
注意:attempt
メソッドがtrue
を返す場合、そのユーザーはアプリケーションにログイン中だと考えられます。Note: If the
attempt
method returns
true
, the user is considered logged
into the application.
ユーザーがRemember meで認証されているかを判定するDetermining If User Authed Via Remember
ユーザーのログインを覚えておく設定の場合、viaRemember
メソッドを使用し、そのユーザーが"remember
me"(ログインしたままにする)クッキーを使用して認証されているのかを判定できます。If you are
"remembering" user logins, you may use the
viaRemember
method to determine if the
user was authenticated using the "remember
me" cookie:
if (Auth::viaRemember())
{
//
}
条件付きのユーザー認証を行うAuthenticating A User With Conditions
認証のクエリーに条件を追加することも可能です。You also may add extra conditions to the authenticating query:
if (Auth::attempt(array('email' => $email, 'password' => $password, 'active' => 1)))
{
// このユーザーは存在しており、アクティブで、使用停止ではない
}
**注目:**Session Fixation攻撃に対抗するため、認証後はセッションIDが自動的に再生成されます。Note: For added protection against session fixation, the user's session ID will automatically be regenerated after authenticating.
ログインしたユーザーにアクセスするAccessing The Logged In User
一度ユーザーが認証されると、Userモデル/レコードにアクセスできます。Once a user is authenticated, you may access the User model / record:
$email = Auth::user()->email;
認証済みのユーザーのIDを取得するには、id
メソッドを使用します。To retrieve the authenticated
user's ID, you may use the id
method:
$id = Auth::id();
アプリケーションにユーザーをIDでログインさせたい時は、loginUsingId
メソッドを使用してください。To simply 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))
{
//
}
そのセッションの間だけユーザーをログインさせる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))
{
//
}
アプリケーションからログアウトするLogging A User Out Of The Application
Auth::logout();
ユーザーの手動ログインManually Logging In Users
既に存在しているユーザーをアプリケーションにログインさせる場合、そのインスタンスを指定し、login
メソッドを呼び出してください。If you need to log an existing
user instance into your application, you may simply
call the login
method with the
instance:
$user = User::find(1);
Auth::login($user);
これはユーザー情報をもとにログインさせるattempt
と同じ状態になります。This is equivalent to logging in
a user via credentials using the
attempt
method.
ルートの保護Protecting Routes
特定のルートへ認証済みのユーザーだけがアクセスできるように、ルートフィルターを使用できます。Laravelはデフォルトのauth
フィルターをapp/filters.php
で定義しています。Route filters may be used to
allow only authenticated users to access a given
route. Laravel provides the auth
filter
by default, and it is defined in
app/filters.php
.
ルートを保護するProtecting A Route
Route::get('profile', array('before' => 'auth', function()
{
// 認証済みのユーザーのみ入れる...
}));
CSRFからの保護CSRF Protection
LaravelはCSRFからアプリケーションを簡単に守る手段を提供しています。Laravel provides an easy method of protecting your application from cross-site request forgeries.
CSRFトークンをフォームへ埋め込むInserting CSRF Token Into Form
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
送信されてきたCSRFトークンをバリデートするValidate The Submitted CSRF Token
Route::post('register', array('before' => 'csrf', function()
{
return '有効なCSRFトークンです!';
}));
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
filter to your
route:
HTTP基本認証でルートを保護するProtecting A Route With HTTP Basic
Route::get('profile', array('before' => 'auth.basic', function()
{
// 認証済みのユーザーのみ入れる...
}));
デフォルトで、basic
フィルターはユーザーレコードのemail
カラムを認証に使用します。ユーザーの他のカラムを使用する場合は、app/filters.php
の中で、そのカラム名をbasic
メソッドの最初の引数として渡してください。By default, the
basic
filter will use the
email
column on the user record when
authenticating. If you wish to use another column
you may pass the column name as the first parameter
to the basic
method in your
app/filters.php
file:
Route::filter('auth.basic', function()
{
return Auth::basic('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 filter
that returns the onceBasic
method:
Route::filter('basic.once', function()
{
return Auth::onceBasic();
});
PHP
FastCGIを使用している場合、デフォルトでHTTP基本認証は正しく動作しません。.htaccess
ファイルに以下の行を追加してください。If you are using PHP FastCGI,
HTTP Basic authentication will not work correctly by
default. 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はパスワードリマインダーを送信し、パスワードをリセットする便利なメソッドを提供しています。最初にIlluminate\Auth\Reminders\RemindableInterface
がUser
モデルへ確実に実装されていることを確認してください。もちろん、フレームワークに含まれるUser
モデルには、このインターフェイスが最初から実装されています。そしてインターフェイスの実装に必要なメソッドを含んでいる、Illuminate\Auth\Reminders\RemindableTrait
を使用しています。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. To get started, verify that your
User
model implements the
Illuminate\Auth\Reminders\RemindableInterface
contract. Of course, the User
model
included with the framework already implements this
interface, and uses the
Illuminate\Auth\Reminders\RemindableTrait
to include the methods needed to implement the
interface.
RemindableInterfaceを実装するImplementing The RemindableInterface
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements RemindableInterface {
use RemindableTrait;
}
リマインダーテーブルのマイグレーションを生成するGenerating The Reminder Table Migration
次に、パスワードリセットトークンを保存するテーブルを生成します。このテーブルのマイグレーションを生成するためには、単にArtisanコマンドのauth::reminders
を実行するだけです。Next, a table must be created to
store the password reset tokens. To generate a
migration for this table, simply execute the
auth:reminders-table
Artisan
command:
php artisan auth:reminders-table
php artisan migrate
パスワードリマインダーコントローラーPassword Reminder Controller
これでパスワードリマインダーコントローラーを生成する準備が整いました。auth:reminders-controller
Artisanコマンドを使用し、コントローラーを自動的に生成しましょう。app/controllers
ディレクトリー中に、RemindersController.php
を生成します。Now we're ready to generate the
password reminder controller. To automatically
generate a controller, you may use the
auth:reminders-controller
Artisan
command, which will create a
RemindersController.php
file in your
app/controllers
directory.
php artisan auth:reminders-controller
生成されたコントローラーには、あなたが表示したパスワードリマインダーフォームを処理する、getRemind
メソッドが既に用意されています。あなたが行う必要があるのは、password.remind
ビューを作成することだけです。このビューはemail
フィールドを持つ、基本的なフォームです。フォームはRemindersController@postRemind
アクションへPOSTする必要があります。The generated controller will
already have a getRemind
method that
handles showing your password reminder form. All you
need to do is create a password.remind
view[/docs/4.2/responses#views]. This view
should have a basic form with an email
field. The form should POST to the
RemindersController@postRemind
action.
シンプルなpassword.remind
ビューは以下のようになるでしょう。A simple form on the
password.remind
view might look like
this:
<form action="{{ action('RemindersController@postRemind') }}" method="POST">
<input type="email" name="email">
<input type="submit" value="Send Reminder">
</form>
getRemind
に加えて、生成されたコントローラーはpostRemind
メソッドも持っています。これはパスワードリマインダーメールをユーザーに送信する処理を行います。このメソッドは、POST
変数にemail
フィールドが存在していることを期待しています。リマインダーメールがユーザーへ無事に送られれば、status
メッセージがフラッシュデーターとしてセッションに保存されます。送信に失敗すれば、error
メッセージが保存されます。In addition to
getRemind
, the generated controller
will already have a postRemind
method
that handles sending the password reminder e-mails
to your users. This method expects the
email
field to be present in the
POST
variables. If the reminder e-mail
is successfully sent to the user, a
status
message will be flashed to the
session. If the reminder fails, an
error
message will be flashed
instead.
postRemind
コントローラーメソッドの中では、ユーザーへ送信する前に、メッセージインスタンスを更新することができます。Within the
postRemind
controller method you may
modify the message instance before it is sent to the
user:
Password::remind(Input::only('email'), function($message)
{
$message->subject('Password Reminder');
});
ユーザーはコントローラーのgetReset
メソッドへルーティングされるリンクを含んだメールを受け取ります。指定されたパスワードリマインダーを識別するために使用されるパスワードリマインダートークンも一緒に送信されてきます。アクションにはpassword.reset
ビューを返すように、予めコードされていますが、このビューも作成して下さい。トークンはビューに渡され、token
という名前の隠しフォーム隠しフィールドとして設置されなくてはなりません。このtoken
に加え、パスワードリセットフォームにはemail
とpassword
、password_confirmation
フィールドが必要です。フォームはRemaindersController@postReset
メソッドへPOSTで送信して下さい。Your user will receive an e-mail
with a link that points to the getReset
method of the controller. The password reminder
token, which is used to identify a given password
reminder attempt, will also be passed to the
controller method. The action is already configured
to return a password.reset
view which
you should build. The token
will be
passed to the view, and you should place this token
in a hidden form field named token
. In
addition to the token
, your password
reset form should contain email
,
password
, and
password_confirmation
fields. The form
should POST to the
RemindersController@postReset
method.
シンプルなpassword.reset
ビューは下のようになるでしょう。A simple form on the
password.reset
view might look like
this:
<form action="{{ action('RemindersController@postReset') }}" method="POST">
<input type="hidden" name="token" value="{{ $token }}">
<input type="email" name="email">
<input type="password" name="password">
<input type="password" name="password_confirmation">
<input type="submit" value="Reset Password">
</form>
最後に、postReset
メソッドがストレージ上のパスワードを実際に変更する責任を負います。このコントローラーアクションの中で、Password::reset
メソッドに渡されたクロージャーは、User
にpassword
属性をセットし、save
メソッドを呼び出しています。もちろん、このクロージャーは、User
モデルがEloquentモデルであると想定しています。しかしながら、アプリケーションのデータベース保管システムに適するように、必要に応じて自由に変更して下さい。Finally, the
postReset
method is responsible for
actually changing the password in storage. In this
controller action, the Closure passed to the
Password::reset
method sets the
password
attribute on the
User
and calls the save
method. Of course, this Closure is assuming your
User
model is an Eloquent
model[/docs/4.2/eloquent]; however, you are
free to change this Closure as needed to be
compatible with your application's database storage
system.
パスワードがうまくリセットし終えたら、ユーザーはアプリケーションのルートへリダイレクトされます。このリダイレクトURLも自由に変更して下さい。パスワードリセットが失敗したら、ユーザーはリセットフォームへ戻るようにリダイレクトされます。そして、error
メッセージがセッションにフラッシュデーターとして保存されます。If the password is successfully
reset, the user will be redirected to the root of
your application. Again, you are free to change this
redirect URL. If the password reset fails, the user
will be redirect back to the reset form, and an
error
message will be flashed to the
session.
パスワードのバリデーションPassword Validation
デフォルトでは、Password::reset
メソッドは確認領域と同一であることと、6文字以上であることを確認します。クロージャーを使うPassword::validator
メソッドで、このルールを変更できます。クロージャーの中でどんなパスワードバリデーションも実行できます。パスワードが確認フィールドと一致するかを調べる必要がないことに注意して下さい。これはフレームワークにより、自動的に調べられます。By default, the
Password::reset
method will verify that
the passwords match and are >= six characters.
You may customize these rules using the
Password::validator
method, which
accepts a Closure. Within this Closure, you may do
any password validation you wish. Note that you are
not required to verify that the passwords match, as
this will be done automatically by the
framework.
Password::validator(function($credentials)
{
return strlen($credentials['password']) >= 6;
});
Note: デフォルトでは、パスワードのリセットトークンは1時間で無効になります。
app/config/auth.php
ファイルのreminder.expire
オプションにより、この時間を変更できます。Note: By default, password reset tokens expire after one hour. You may change this via thereminder.expire
option of yourapp/config/auth.php
file.
暗号化Encryption
Laravelはmcrypt PHP拡張による、強力なAES暗号化機能を提供しています。Laravel provides facilities for strong AES encryption via the mcrypt PHP extension:
値を暗号化するEncrypting A Value
$encrypted = Crypt::encrypt('secret');
注目:
app/config/app.php
ファイルのkey
オプションに16文字か24文字、32文字のランダムな文字列を確実に設定してください。そうしないと、暗号化された値は安全ではありません。Note: Be sure to set a 16, 24, or 32 character random string in thekey
option of theapp/config/app.php
file. Otherwise, encrypted values will not be secure.
値を解読するDecrypting A Value
$decrypted = Crypt::decrypt($encryptedValue);
手法とモードを設定するSetting The Cipher & Mode
暗号化に使用する手法とモードもセットできます。You may also set the cipher and mode used by the encrypter:
Crypt::setMode('ctr');
Crypt::setCipher($cipher);
認証ドライバーAuthentication Drivers
Laravelでは最初から、database
とeloquent
認証ドライバーが用意されています。他の認証ドライバーを追加するための情報は、認証の拡張に関するドキュメントをご覧ください。Laravel offers the
database
and eloquent
authentication drivers out of the box. For more
information about adding additional authentication
drivers, check out the Authentication extension
documentation[/docs/4.2/extending#authentication].