Laravel 5.1では、インストールからすぐに使用できた認証もLaravel5.3ではインストール直後の状態では利用することはできません。しかし、Laravel5.1同様簡単にAuth(認証) 機能を利用することができます。
make:authコマンド実行でAuth(認証)開始、
Laravel5.2からphp artisanのmake:authコマンドが新たに追加され、このコマンドを実行するとAuth(認証)に必要なファイルが作成され、すぐにAuth(認証)を開始することができます。
$ php artisan make:auth
Authentication scaffolding generated successfully.
make:authで作成されるファイル
make:authコマンドを実行するとAuthentication scaffolding generated successfullyと出力されますが、一体何が作成されたのかはわかりません。
上記のメッセージの意味は、認証に必要になるベースのファイル群が正常に生成されましたという感じになるでしょうか。
メッセージの通り、Auth(認証)に必要となるファイル群が作成されていますが、大きく分けると3箇所に変更が加えられます。
- HomeController.phpの追加
- web.phpにAuth(認証)に関するルーティングが追加
- ログイン、登録、パスワードリセットのViewファイルの追加
また、/(ルート)の初期画面には、LOGINとREGISTERへのリンクが追加されています。
HomeController.phpの追加
app/Http/Controllers/以下にHomeController.phpが作成されます。
web.phpにAuth(認証)に関するルーティングが追加
また、ルーティング情報が記載されているweb.phpも更新され、Auth(認証)に関するルーティングが追加されています。
web.php
Auth::routes();
Route::get('/home', 'HomeController@index');
ログイン、登録、パスワードリセットのViewファイルの追加
ログイン画面などに必要となるviewファイルがviewsディレクトリ内に作成されています。
resources/viewsディレクトリには、auth, layouts, home.blade.php等が作成されています。
$ ls
auth base.blade.php errors home.blade.php layouts vendor welcome.blade.php
ログイン画面へのリンク
ブラウザで、'/'(ルート)にアクセスするとインストール直後では、中央にLaravelとその下にリンクが張られていますが、
make:authを実行後は、右上にLoginとRegisterのリンクが追加されます。
ユーザの登録
※ユーザの登録を行うためには、データベースの設定を行い、php arisan migrateコマンドを実行して、UserテーブルとPassword_Resetsテーブルを 作成しておく必要があります。
REGISTERのリンクからユーザ登録画面に移動します。
ユーザ情報を入れて、Registerボタンを押すとユーザの登録と同時にログインも完了します。
ログイン後は、URLの/homeにリダイレクトされます。
App\Http\Controllers\Auth\LoginController.phpの中にログイン後のリダイレクト先が記載されているので、変更を行うことができます。
LoginCotroller.php
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';
web.phpでのAuth(認証)のルーティング
web.phpでauthのルーティングをもう少し詳しく見ていくとログイン、ユーザ登録画面へのルーティングが下記の1行にまとめられています。
web.php
Auth::routes();
何が実行されているか確認するためにroutes()のメソッドを持つIlluminate\Support\Facades\Auth.phpを確認します。
Auth.php
public static function routes()
{
static::$app->make('router')->auth();
}
今度は、auth()の中身を確認するために、Illuminate\Routing\Routing.phpを確認します。Routing.phpには、Laravel5.1では、デフォルトでroutes.phpに記載されていた、ルーティング情報が記載されています。
Routing.php
public function auth()
{
// Authentication Routes...
$this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController@login');
$this->post('logout', 'Auth\LoginController@logout');
// Registration Routes...
$this->get('register', 'Auth\RegisterController@showRegistrationForm');
$this->post('register', 'Auth\RegisterController@register');
// Password Reset Routes...
$this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm');
$this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
$this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm');
$this->post('password/reset', 'Auth\ResetPasswordController@reset');
}
Laravelの認証の3つのパート
auth()の中身を見てわかるようにLaravelのAuth(認証)は大きく3つのパートに分かれていることがわかるかと思います。
- ログイン(Authentication Routes)
- ユーザの登録(Registration Routes)
- パスワードリセット(Password Reset Routes)
詳細には踏み込みませんが、ログイン処理を行う下記のルーティングの一行で流れを追ってみましょう。
Routing.php
$this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
ブラウザからログイン画面が出力される/loginにアクセスするとAuth\LoginController@showLoginForm'が実行されます。
showLoginFormメソッドは、App\Http\Controllers\Auth\LoginController.phpのtraitである Illuminate\Foundation\Auth\AuthenticatesUsersに記載されており、auth.loginのViewを表示させています。
AuthenticatesUsers.php
public function showLoginForm()
{
return view('auth.login');
}
複数のファイルにまたがっていますが、/loginにアクセスするとauth.loginのViewファイルに記載されているログイン画面が出力されるという流れになっています。
出力されたログイン画面にE-mailとパスワードを入れると/loginに入力した値がPOSTされ、下記のログイン処理が行われます。
Routing.php
$this->post('login', 'Auth\LoginController@login');
ログイン処理では、E-mailとパスワードがチェックされ、エラーになった場合、ログイン画面にエラー情報と一緒に戻されます。
ログインの試行回数も記録されており、閾値に達するとログインが一時的に不可になるといった流れになっています。
AuthenticatesUsers.php
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->credentials($request);
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
ページに認証をかける
make:authを実行すると/homeへのルーティングが追加されています。
web.php
Route::get('/home', 'HomeController@index');
/homeにアクセスするとHomeController@indexが実行されるので、中身を確認してみます。
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
$this->middleware('auth')のmiddlewareで/homeへのアクセスにAuth(認証)がかけられていることがわかります。
コンストラクタ__construct()を使用しているので、アクセスが行われる度にAuth(認証)が行われています。
そのため、ログインしていない状態で/homeにアクセスすると/login画面にリダイレクトされることになり、/login画面でE-mailとパスワードを入力することになります。
ここまでの流れを見てきたとおり、Laravel5.3では、データベースへのUserテーブルの作成とmake:authコマンドを実行するだけで、Auth(認証)機能を組み込むことができます。