Laravel 8からは、認証機能のscaffoldとして、これまで推奨されていたLaravel UIの代わりに、Laravel Jetstreamが推奨されるようになりました(Laravel 8でも使用することはできます)。しかし、このLaravel Jetstreamが高機能で見た目が良いかわりに、細かなカスタマイズがしにくいことから、Laravel UIを採用するケースもあるようです。
認証機能の実装については、これらのライブラリを使用する他に、Laravelの認証クラスを直接使って、自前の認証機能を実装することもできます。
そこで、今回はLaravelのブラウザ認証クラスの処理の流れをコードを示しながら紹介します。
認証機能では、guard
とprovider
が重要な概念となります。
guard
は、リクエスト毎にユーザーを認証する方法を定義しています。これには、セッションストレージとクッキーを使って状態を保持するSessionGuard
と、トークンを使って認証するTokenGuard
があります。
provider
はデータベースなどの永続ストレージから、ユーザーを取得する方法を定義しています。これには、Eloquent
を使うEloquentUserProvider
と、クエリビルダーを使うDatabaseUserProvider
があります。
また、guard
とprovider
を自前で実装することもできます。
それでは、実際にコードを見てみましょう。
ログイン時、コントローラでは、Auth
ファサードのattempt()
メソッドでユーザーを認証します。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class LoginController { public function login(Request $request) { $credentials = $request->only('email', 'password'); if (Auth::attempt($credentials)) { return redirect()->intended(); } } }
Auth::attempt()
に認証で使用するパラメータの配列を渡します。実際には、SessionGuard
クラスのattempt()
メソッドが呼ばれます。
また、ログイン状態を維持したい場合は、attempt()
メソッドの第2引数にtrue
を渡します。
なお、ユーザーを取得する条件は、例の通りである必要はありません。たとえば、email
の代わりに、user_code
などの何らかのユニークなカラムを指定することができます。さらに、credentials['role'] = 1;
などのように、追加の条件を付加することもできます。
Auth
ファサードのguard()
メソッドを使うと、使いたいguardインスタンスを指定することができます。これにより、異なる複数の認証処理を併用することができます。
if (Auth::guard('other_auth')->attempt($credentials)) { // }
SessionGuard
クラスでは、ユーザの認証、RememberTokenの更新、認証済みのユーザーインスタンスへのアクセスなどの機能を提供します。
SessionGuard
クラスのattempt()
メソッドを抜粋しました。順番に処理を見てきます。
<?php namespace Illuminate\Auth; // use ... class SessionGuard implements StatefulGuard, SupportsBasicAuth { use GuardHelpers, Macroable; // ... /** * Attempt to authenticate a user using the given credentials. * * @param array $credentials * @param bool $remember * @return bool */ public function attempt(array $credentials = [], $remember = false) { $this->fireAttemptEvent($credentials, $remember); $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials); // If an implementation of UserInterface was returned, we'll ask the provider // to validate the user against the given credentials, and if they are in // fact valid we'll log the users into the application and return true. if ($this->hasValidCredentials($user, $credentials)) { $this->login($user, $remember); return true; } // If the authentication attempt fails we will fire an event so that the user // may be notified of any suspicious attempts to access their account from // an unrecognized user. A developer may listen to this event as needed. $this->fireFailedEvent($user, $credentials); return false; } // ... }
初めにfireAttemptEvent()
メソッドが呼ばれ、Attempting
イベントが発行されます。
/** * Fire the attempt event with the arguments. * * @param array $credentials * @param bool $remember * @return void */protected function fireAttemptEvent(array $credentials, $remember = false) { if (isset($this->events)) { $this->events->dispatch(new Attempting( $this->name, $credentials, $remember )); } }
ここでは、auth.php
で指定したUserProvider
のretrieveByCredentials()
メソッドが呼ばれ、Illuminate\Contracts\Auth\Authenticatable
、もしくは、null
が返却されます。
ここでは、(1)渡された認証情報を検証し、(2)成功すればイベントを発行します。
/** * Determine if the user matches the credentials. * * @param mixed $user * @param array $credentials * @return bool */protected function hasValidCredentials($user, $credentials) { // (1) $validated = ! is_null($user) && $this->provider->validateCredentials($user, $credentials); // (2) if ($validated) { $this->fireValidatedEvent($user); } return $validated; }
ここでは、(1)セッションストレージのIDを更新し、$remember
がtrueかつ、RememberTokenが空の場合、(2)新しいRememberTokenを発行して、(3)クッキーが更新されます。その後、(4)Login
イベントが発行されて、認証されたユーザーがセットされ、Authenticated
イベントが発行されます。
/** * Log a user into the application. * * @param \Illuminate\Contracts\Auth\Authenticatable $user * @param bool $remember * @return void */public function login(AuthenticatableContract $user, $remember = false) { // (1) $this->updateSession($user->getAuthIdentifier()); // If the user should be permanently "remembered" by the application we will // queue a permanent cookie that contains the encrypted copy of the user // identifier. We will then decrypt this later to retrieve the users. if ($remember) { // (2) $this->ensureRememberTokenIsSet($user); // (3) $this->queueRecallerCookie($user); } // (4) // If we have an event dispatcher instance set we will fire an event so that // any listeners will hook into the authentication events and run actions // based on the login and logout events fired from the guard instances. $this->fireLoginEvent($user, $remember); // (5) $this->setUser($user); }
hasValidCredentials()
メソッドで検証に失敗した場合、Failed
イベントが発行されます
/** * Fire the failed authentication attempt event with the given arguments. * * @param \Illuminate\Contracts\Auth\Authenticatable|null $user * @param array $credentials * @return void */protected function fireFailedEvent($user, array $credentials) { if (isset($this->events)) { $this->events->dispatch(new Failed( $this->name, $user, $credentials )); } }
UserProvider
は、データベースなどの永続ストレージからユーザーを取得する機能を提供します。
SessionGuard
クラスのattempt()
メソッドから呼ばれます。渡されたcredentials
をもとにユーザーを取得し、model
を返却します。
(1)渡されたcredentials
をチェックし、問題があればnull
を返却します。(2)認証用のmodel
を返却します。(3)認証のためのクエリを組み立てます。(4)最初に見つかったユーザーを返却します。
/** * Retrieve a user by the given credentials. * * @param array $credentials * @return \Illuminate\Contracts\Auth\Authenticatable|null */public function retrieveByCredentials(array $credentials) { // (1) if (empty($credentials) || (count($credentials) === 1 && Str::contains($this->firstCredentialKey($credentials), 'password'))) { return; } // (2) // First we will add each credential element to the query as a where clause. // Then we can execute the query and, if we found a user, return it in a // Eloquent User "model" that will be utilized by the Guard instances. $query = $this->newModelQuery(); foreach ($credentials as $key => $value) { if (Str::contains($key, 'password')) { continue; } // (3) if (is_array($value) || $value instanceof Arrayable) { $query->whereIn($key, $value); } else { $query->where($key, $value); } } // (4) return $query->first(); }
SessionGuard
クラスのuserFromRecaller
メソッドから呼ばれます。渡されたユーザーを識別する値をもとにユーザーを取得し、そのユーザーのRememberTokenとユーザーを比較して、model
またはnull
を返却します。
(1)認証用のmodel
を返却します。(2)認証のためのクエリを組み立て、最初に見つかったユーザーを返却します。(3)ユーザーが見つからなければnull
を返却します。(4)見つかったユーザーのRememberTokenを取得します。(5)渡されたRememberTokenとユーザーのRememberTokenを比較し、一致すればユーザーを、一致しなければnull
を返却します。
/** * Retrieve a user by their unique identifier and "remember me" token. * * @param mixed $identifier * @param string $token * @return \Illuminate\Contracts\Auth\Authenticatable|null */public function retrieveByToken($identifier, $token) { // (1) $model = $this->createModel(); // (2) $retrievedModel = $this->newModelQuery($model)->where( $model->getAuthIdentifierName(), $identifier )->first(); // (3) if (! $retrievedModel) { return; } // (4) $rememberToken = $retrievedModel->getRememberToken(); // (5) return $rememberToken && hash_equals($rememberToken, $token) ? $retrievedModel : null; }
EloquentUserProvider
と同じく、データベースなどの永続ストレージからユーザーを取得する機能を提供します。EloquentUserProvider
では、ユーザーの取得にEloquentを使っていましたが、こちらはクエリビルダーを使います。
SessionGuard
クラスのattempt()
メソッドから呼ばれます。渡されたcredentials
をもとにユーザーを取得し、model
を返却します。
(1)渡されたcredentials
をチェックし、問題があればnull
を返却します。(2)認証のためのクエリを返却します。(3)認証のためのクエリを組み立てます。(4)最初に見つかったユーザーを返却します。(5)ユーザーをIlluminate\Auth\GenericUser
に変換して返却します。
/** * Retrieve a user by the given credentials. * * @param array $credentials * @return \Illuminate\Contracts\Auth\Authenticatable|null */public function retrieveByCredentials(array $credentials) { // (1) if (empty($credentials) || (count($credentials) === 1 && array_key_exists('password', $credentials))) { return; } // (2) // First we will add each credential element to the query as a where clause. // Then we can execute the query and, if we found a user, return it in a // generic "user" object that will be utilized by the Guard instances. $query = $this->conn->table($this->table); foreach ($credentials as $key => $value) { if (Str::contains($key, 'password')) { continue; } // (3) if (is_array($value) || $value instanceof Arrayable) { $query->whereIn($key, $value); } else { $query->where($key, $value); } } // (4) // Now we are ready to execute the query to see if we have an user matching // the given credentials. If not, we will just return nulls and indicate // that there are no matching users for these given credential arrays. $user = $query->first(); // (5) return $this->getGenericUser($user); }
SessionGuard
クラスのuserFromRecaller
メソッドから呼ばれます。渡されたユーザーを識別する値をもとにユーザーを取得し、そのユーザーのRememberTokenとユーザーを比較して、model
またはnull
を返却します。
(1)認証のためのクエリを組み立て、最初に見つかったユーザーを返却します。(2)渡されたRememberTokenとユーザーのRememberTokenを比較し、一致すればユーザーを、一致しなければnull
を返却します。
/** * Retrieve a user by their unique identifier and "remember me" token. * * @param mixed $identifier * @param string $token * @return \Illuminate\Contracts\Auth\Authenticatable|null */public function retrieveByToken($identifier, $token) { // (1) $user = $this->getGenericUser( $this->conn->table($this->table)->find($identifier) ); // (2) return $user && $user->getRememberToken() && hash_equals($user->getRememberToken(), $token) ? $user : null; }
Laravelのブラウザ認証の流れをコードを示しながら紹介しました。API認証の方も、似たような流れになっています。API認証に興味があれば、よければこちらの記事もご覧ください。