はじめに
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
を自前で実装することもできます。
それでは、実際にコードを見てみましょう。
Controller
ログイン時、コントローラでは、Auth
ファサードのattempt()
メソッドでユーザーを認証します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php namespaceApp\Http\Controllers; useIlluminate\Http\Request; useIlluminate\Support\Facades\Auth; classLoginController { publicfunctionlogin(Request$request) { $credentials=$request->only('email','password'); if(Auth::attempt($credentials)){ returnredirect()->intended(); } } } |
Auth::attempt()
に認証で使用するパラメータの配列を渡します。実際には、SessionGuard
クラスのattempt()
メソッドが呼ばれます。
また、ログイン状態を維持したい場合は、attempt()
メソッドの第2引数にtrue
を渡します。
なお、ユーザーを取得する条件は、例の通りである必要はありません。たとえば、email
の代わりに、user_code
などの何らかのユニークなカラムを指定することができます。さらに、credentials['role'] = 1;
などのように、追加の条件を付加することもできます。
Auth
ファサードのguard()
メソッドを使うと、使いたいguardインスタンスを指定することができます。これにより、異なる複数の認証処理を併用することができます。
1 2 3 | if(Auth::guard('other_auth')->attempt($credentials)){ // } |
SessionGuard
SessionGuard
クラスでは、ユーザの認証、RememberTokenの更新、認証済みのユーザーインスタンスへのアクセスなどの機能を提供します。
SessionGuard
クラスのattempt()
メソッドを抜粋しました。順番に処理を見てきます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <?php namespaceIlluminate\Auth; // use ... classSessionGuard implementsStatefulGuard,SupportsBasicAuth { useGuardHelpers,Macroable; // ... /** * Attempt to authenticate a user using the given credentials. * * @param array $credentials * @param bool $remember * @return bool */ publicfunctionattempt(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); returntrue; } // 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); returnfalse; } // ... } |
fireAttemptEvent
初めにfireAttemptEvent()
メソッドが呼ばれ、Attempting
イベントが発行されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | /** * Fire the attempt event with the arguments. * * @param array $credentials * @param bool $remember * @return void */ protectedfunctionfireAttemptEvent(array$credentials,$remember=false) { if(isset($this->events)){ $this->events->dispatch(newAttempting( $this->name,$credentials,$remember )); } } |
retrieveByCredentials
ここでは、auth.php
で指定したUserProvider
のretrieveByCredentials()
メソッドが呼ばれ、Illuminate\Contracts\Auth\Authenticatable
、もしくは、null
が返却されます。
hasValidCredentials
ここでは、(1)渡された認証情報を検証し、(2)成功すればイベントを発行します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | /** * Determine if the user matches the credentials. * * @param mixed $user * @param array $credentials * @return bool */ protectedfunctionhasValidCredentials($user,$credentials) { // (1) $validated=!is_null($user)&&$this->provider->validateCredentials($user,$credentials); // (2) if($validated){ $this->fireValidatedEvent($user); } return$validated; } |
login
ここでは、(1)セッションストレージのIDを更新し、$remember
がtrueかつ、RememberTokenが空の場合、(2)新しいRememberTokenを発行して、(3)クッキーが更新されます。その後、(4)Login
イベントが発行されて、認証されたユーザーがセットされ、Authenticated
イベントが発行されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /** * Log a user into the application. * * @param \Illuminate\Contracts\Auth\Authenticatable $user * @param bool $remember * @return void */ publicfunctionlogin(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); } |
fireFailedEvent
hasValidCredentials()
メソッドで検証に失敗した場合、Failed
イベントが発行されます
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | /** * Fire the failed authentication attempt event with the given arguments. * * @param \Illuminate\Contracts\Auth\Authenticatable|null $user * @param array $credentials * @return void */ protectedfunctionfireFailedEvent($user,array$credentials) { if(isset($this->events)){ $this->events->dispatch(newFailed( $this->name,$user,$credentials )); } } |
EloquentUserProvider
UserProvider
は、データベースなどの永続ストレージからユーザーを取得する機能を提供します。
retrieveByCredentials
SessionGuard
クラスのattempt()
メソッドから呼ばれます。渡されたcredentials
をもとにユーザーを取得し、model
を返却します。
(1)渡されたcredentials
をチェックし、問題があればnull
を返却します。(2)認証用のmodel
を返却します。(3)認証のためのクエリを組み立てます。(4)最初に見つかったユーザーを返却します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | /** * Retrieve a user by the given credentials. * * @param array $credentials * @return \Illuminate\Contracts\Auth\Authenticatable|null */ publicfunctionretrieveByCredentials(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($credentialsas$key=>$value){ if(Str::contains($key,'password')){ continue; } // (3) if(is_array($value)||$valueinstanceofArrayable){ $query->whereIn($key,$value); }else{ $query->where($key,$value); } } // (4) return$query->first(); } |
retrieveByToken
SessionGuard
クラスのuserFromRecaller
メソッドから呼ばれます。渡されたユーザーを識別する値をもとにユーザーを取得し、そのユーザーのRememberTokenとユーザーを比較して、model
またはnull
を返却します。
(1)認証用のmodel
を返却します。(2)認証のためのクエリを組み立て、最初に見つかったユーザーを返却します。(3)ユーザーが見つからなければnull
を返却します。(4)見つかったユーザーのRememberTokenを取得します。(5)渡されたRememberTokenとユーザーのRememberTokenを比較し、一致すればユーザーを、一致しなければnull
を返却します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /** * Retrieve a user by their unique identifier and "remember me" token. * * @param mixed $identifier * @param string $token * @return \Illuminate\Contracts\Auth\Authenticatable|null */ publicfunctionretrieveByToken($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; } |
DatabaseUserProvider
EloquentUserProvider
と同じく、データベースなどの永続ストレージからユーザーを取得する機能を提供します。EloquentUserProvider
では、ユーザーの取得にEloquentを使っていましたが、こちらはクエリビルダーを使います。
retrieveByCredentials
SessionGuard
クラスのattempt()
メソッドから呼ばれます。渡されたcredentials
をもとにユーザーを取得し、model
を返却します。
(1)渡されたcredentials
をチェックし、問題があればnull
を返却します。(2)認証のためのクエリを返却します。(3)認証のためのクエリを組み立てます。(4)最初に見つかったユーザーを返却します。(5)ユーザーをIlluminate\Auth\GenericUser
に変換して返却します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | /** * Retrieve a user by the given credentials. * * @param array $credentials * @return \Illuminate\Contracts\Auth\Authenticatable|null */ publicfunctionretrieveByCredentials(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($credentialsas$key=>$value){ if(Str::contains($key,'password')){ continue; } // (3) if(is_array($value)||$valueinstanceofArrayable){ $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); } |
retrieveByToken
SessionGuard
クラスのuserFromRecaller
メソッドから呼ばれます。渡されたユーザーを識別する値をもとにユーザーを取得し、そのユーザーのRememberTokenとユーザーを比較して、model
またはnull
を返却します。
(1)認証のためのクエリを組み立て、最初に見つかったユーザーを返却します。(2)渡されたRememberTokenとユーザーのRememberTokenを比較し、一致すればユーザーを、一致しなければnull
を返却します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | /** * Retrieve a user by their unique identifier and "remember me" token. * * @param mixed $identifier * @param string $token * @return \Illuminate\Contracts\Auth\Authenticatable|null */ publicfunctionretrieveByToken($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認証に興味があれば、よければこちらの記事もご覧ください。