Laravel-swoole: Auth is not resolving for every request

Created on 16 Aug 2018  路  5Comments  路  Source: swooletw/laravel-swoole

  1. Please provide your PHP and Swoole version. (php -v and php --ri swoole)
    PHP: 7.2.8
    Swoole: 4.04

  2. Please provide your Laravel/Lumen version.
    Laravel: 5.6.33

  3. Which release version of this package are you using?
    Laravel Swoole: 2.4.1

  4. What did you do? If possible, provide a recipe for reproducing the error.

  5. Installed fresh version of Laravel Backpack (CRUD admin panel) (base - 0.9.7, crud - 3.4.30)
  6. Installed fresh version of Laravel Passport (OAuth) (v6.0.7)
  7. Installed fresh spatie permissions (spatie/laravel-permissions) package (2.14.0)
  8. auth.php config file:
    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    'guards' => [
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ]
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => \App\Models\User::class,
        ],
    ],
  • config/app.php providers and aliases list:
    'providers' => [
        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,
        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,

    ],

    'aliases' => [
        'App' => Illuminate\Support\Facades\App::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
        'Blade' => Illuminate\Support\Facades\Blade::class,
        'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
        'Bus' => Illuminate\Support\Facades\Bus::class,
        'Cache' => Illuminate\Support\Facades\Cache::class,
        'Config' => Illuminate\Support\Facades\Config::class,
        'Cookie' => Illuminate\Support\Facades\Cookie::class,
        'Crypt' => Illuminate\Support\Facades\Crypt::class,
        'DB' => Illuminate\Support\Facades\DB::class,
        'Eloquent' => Illuminate\Database\Eloquent\Model::class,
        'Event' => Illuminate\Support\Facades\Event::class,
        'File' => Illuminate\Support\Facades\File::class,
        'Gate' => Illuminate\Support\Facades\Gate::class,
        'Hash' => Illuminate\Support\Facades\Hash::class,
        'Lang' => Illuminate\Support\Facades\Lang::class,
        'Log' => Illuminate\Support\Facades\Log::class,
        'Mail' => Illuminate\Support\Facades\Mail::class,
        'Notification' => Illuminate\Support\Facades\Notification::class,
        'Password' => Illuminate\Support\Facades\Password::class,
        'Queue' => Illuminate\Support\Facades\Queue::class,
        'Redirect' => Illuminate\Support\Facades\Redirect::class,
        'RedisExt' => Illuminate\Support\Facades\Redis::class,
        'Request' => Illuminate\Support\Facades\Request::class,
        'Response' => Illuminate\Support\Facades\Response::class,
        'Route' => Illuminate\Support\Facades\Route::class,
        'Schema' => Illuminate\Support\Facades\Schema::class,
        'Session' => Illuminate\Support\Facades\Session::class,
        'Storage' => Illuminate\Support\Facades\Storage::class,
        'URL' => Illuminate\Support\Facades\URL::class,
        'Validator' => Illuminate\Support\Facades\Validator::class,
        'View' => Illuminate\Support\Facades\View::class,
    ],
  • app/Providers/AppServiceProvider:
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(): void
    {
        \Validator::extend('uuid', function ($attribute, $value, $parameters, $validator) {
            return \Ramsey\Uuid\Uuid::isValid($value);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register(): void
    {
        Passport::ignoreMigrations();

        $this->app->singleton(\App\Repository\UserRepository::class, function () {
            return new \App\Repository\UserRepository;
        });

        $this->app->singleton(\App\Services\UsersBanService::class, function () {
            return new \App\Services\UsersBanService;
        });
    }
}
  • app/Providers/AuthServiceProvider:
class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot(): void
    {
        $this->registerPolicies();

        Passport::routes();
        Passport::enableImplicitGrant();
    }
}
  • config/swoole_http.php file:
<?php

use Swoole\Table;

return [
    /*
    |--------------------------------------------------------------------------
    | HTTP server configurations.
    |--------------------------------------------------------------------------
    |
    | @see https://www.swoole.co.uk/docs/modules/swoole-server/configuration
    |
    */
    'server' => [
        'host' => env('SWOOLE_HTTP_HOST', '127.0.0.1'),
        'port' => env('SWOOLE_HTTP_PORT', '1215'),
        'public_path' => base_path('public'),
        // Determine if to use swoole to respond request for static files
        'handle_static_files' => env('SWOOLE_HANDLE_STATIC', false),
        'options' => [
            'pid_file' => env('SWOOLE_HTTP_PID_FILE', base_path('storage/logs/swoole_http.pid')),
            'log_file' => env('SWOOLE_HTTP_LOG_FILE', base_path('storage/logs/swoole_http.log')),
            'daemonize' => env('SWOOLE_HTTP_DAEMONIZE', false),
            // Normally this value should be 1~4 times larger according to your cpu cores.
            'reactor_num' => env('SWOOLE_HTTP_REACTOR_NUM', swoole_cpu_num()),
            'worker_num' => env('SWOOLE_HTTP_WORKER_NUM', 1/*swoole_cpu_num()*/),
            'task_worker_num' => env('SWOOLE_HTTP_TASK_WORKER_NUM', swoole_cpu_num()),
            // The data to receive can't be larger than buffer_output_size.
            'package_max_length' => 20 * 1024 * 1024,
            // The data to send can't be larger than buffer_output_size.
            'buffer_output_size' => 10 * 1024 * 1024,
            // Max buffer size for socket connections
            'socket_buffer_size' => 128 * 1024 * 1024,
            // Worker will restart after processing this number of request
            'max_request' => 10000,
            // Enable coroutine send
            'send_yield' => true,
            // You must add --enable-openssl while compiling Swoole
            'ssl_cert_file' => null,
            'ssl_key_file' => null,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Enable to turn on websocket server.
    |--------------------------------------------------------------------------
    */
    'websocket' => [
        'enabled' => env('SWOOLE_HTTP_WEBSOCKET', false),
    ],

    /*
    |--------------------------------------------------------------------------
    | Console output will be transferred to response content if enabled.
    |--------------------------------------------------------------------------
    */
    'ob_output' => env('SWOOLE_OB_OUTPUT', false),

    /*
    |--------------------------------------------------------------------------
    | Instances here will be cleared on every request.
    |--------------------------------------------------------------------------
    */
    'instances' => [
//        'auth'
    ],

    /*
    |--------------------------------------------------------------------------
    | Providers here will be registered on every request.
    |--------------------------------------------------------------------------
    */
    'providers' => [
        Illuminate\Pagination\PaginationServiceProvider::class,
        Laravel\Passport\PassportServiceProvider::class
    ],

    /*
    |--------------------------------------------------------------------------
    | Define your swoole tables here.
    |
    | @see https://www.swoole.co.uk/docs/modules/swoole-table
    |--------------------------------------------------------------------------
    */
    'tables' => [
        // 'table_name' => [
        //     'size' => 1024,
        //     'columns' => [
        //         ['name' => 'column_name', 'type' => Table::TYPE_STRING, 'size' => 1024],
        //     ]
        // ],
    ]
];
    protected function registerAuthenticator()
    {
        $this->app->singleton('auth', function ($app) {
            var_dump('auth resolved');

            // Once the authentication service has actually been requested by the developer
            // we will set a variable in the application indicating such. This helps us
            // know that we need to set any queued cookies in the after event later.
            $app['auth.loaded'] = true;

            return new AuthManager($app);
        });

        $this->app->singleton('auth.driver', function ($app) {
            return $app['auth']->guard();
        });
    }
  1. What did you expect to see?
    Auth provider resolving for every request

  2. What did you see instead?
    Auth provider was resolved only twice afrer swoole server started:

app-server_1  | Swoole http server started: <http://0.0.0.0:1215>
app-server_1  | string(12) "auth resoved"
app-server_1  | string(12) "auth resoved"

And it's doesn't matter how many requests i perform, auth provider doesn't resolving for request.

question

Most helpful comment

@albertcht thanks. It's fixed my case.

'providers' => [
    Illuminate\Pagination\PaginationServiceProvider::class,
    Illuminate\Auth\AuthServiceProvider::class,
    Spatie\Permission\PermissionServiceProvider::class,
    Laravel\Passport\PassportServiceProvider::class
],

But maybe we should include that to docs?
We need to reset _auth_ for each request and also we need to reset all services which depends on _auth_ service.

All 5 comments

Only possible to uncomment "auth" in "instances" section of laravel swoole config file.
And then auth is resolving for each request.

Please refer to #74 , and try:

'providers' => [
    Illuminate\Pagination\PaginationServiceProvider::class,
    App\Providers\AuthServiceProvider::class,
    App\Providers\AppServiceProvider::class,
    Laravel\Passport\PassportServiceProvider::class
],

@albertcht thanks. It's fixed my case.

'providers' => [
    Illuminate\Pagination\PaginationServiceProvider::class,
    Illuminate\Auth\AuthServiceProvider::class,
    Spatie\Permission\PermissionServiceProvider::class,
    Laravel\Passport\PassportServiceProvider::class
],

But maybe we should include that to docs?
We need to reset _auth_ for each request and also we need to reset all services which depends on _auth_ service.

Thanks for your suggestion, I have added a note in debug guideline.

My custom auth providers were not re-resolving for each request.

For me it was not enough to put AuthServiceProvider under 'providers'; I had to also put 'auth' under 'instances'. This is because Auth::extend() only sets the lazy resolver for the guard; it doesn't clear any previously registered guard.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yl picture yl  路  3Comments

caveman74 picture caveman74  路  7Comments

jiangjiang0228 picture jiangjiang0228  路  8Comments

george-kar picture george-kar  路  6Comments

Arkanius picture Arkanius  路  7Comments