カテゴリー: BackEnd

コードでわかるLaravelのブラウザ認証

はじめに

Laravel 8からは、認証機能のscaffoldとして、これまで推奨されていたLaravel UIの代わりに、Laravel Jetstreamが推奨されるようになりました(Laravel 8でも使用することはできます)。しかし、このLaravel Jetstreamが高機能で見た目が良いかわりに、細かなカスタマイズがしにくいことから、Laravel UIを採用するケースもあるようです。

認証機能の実装については、これらのライブラリを使用する他に、Laravelの認証クラスを直接使って、自前の認証機能を実装することもできます。

そこで、今回はLaravelのブラウザ認証クラスの処理の流れをコードを示しながら紹介します。

認証機能の概要

認証機能では、guardproviderが重要な概念となります。

guardは、リクエスト毎にユーザーを認証する方法を定義しています。これには、セッションストレージとクッキーを使って状態を保持するSessionGuardと、トークンを使って認証するTokenGuardがあります。

providerはデータベースなどの永続ストレージから、ユーザーを取得する方法を定義しています。これには、Eloquentを使うEloquentUserProviderと、クエリビルダーを使うDatabaseUserProviderがあります。

また、guardproviderを自前で実装することもできます。

それでは、実際にコードを見てみましょう。

Controller

ログイン時、コントローラでは、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

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

初めに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
        ));
    }
}

retrieveByCredentials

ここでは、auth.phpで指定したUserProviderretrieveByCredentials()メソッドが呼ばれ、Illuminate\Contracts\Auth\Authenticatable、もしくは、nullが返却されます。

hasValidCredentials

ここでは、(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;
}

login

ここでは、(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);
}

fireFailedEvent

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
        ));
    }
}

EloquentUserProvider

UserProviderは、データベースなどの永続ストレージからユーザーを取得する機能を提供します。

retrieveByCredentials

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();
}

retrieveByToken

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;
}

DatabaseUserProvider

EloquentUserProviderと同じく、データベースなどの永続ストレージからユーザーを取得する機能を提供します。EloquentUserProviderでは、ユーザーの取得にEloquentを使っていましたが、こちらはクエリビルダーを使います。

retrieveByCredentials

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);
}

retrieveByToken

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認証に興味があれば、よければこちらの記事もご覧ください。

おすすめ書籍

 

Hiroki Ono

シェア
執筆者:
Hiroki Ono
タグ: phplaravel

最近の投稿

フロントエンドで動画デコレーション&レンダリング

はじめに 今回は、以下のように…

4週間 前

Goのクエリビルダー goqu を使ってみる

はじめに 最近携わっているとあ…

1か月 前

【Xcode15】プライバシーマニフェスト対応に備えて

はじめに こんにちは、suzu…

2か月 前

FSMを使った状態管理をGoで実装する

はじめに 一般的なアプリケーシ…

3か月 前