Laravel session cookie not encrypted when using AJ

2019-08-26 09:17发布

问题:

I'm about to create a single-sign-on interface for my app. The other app sends an AJAX POST request and I authenticate the user and return a response. A session cookie is beeing set, but it is not encrypted.

The relevant Code

$user = User::where('email', $email)->first();
if ($user) {
  Auth::login($user);
  return response("OK", 200);
}

My 'api' part in Kernel.php

'api' => [
    'throttle:60,1',
    'bindings',
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \App\Http\Middleware\EncryptCookies::class,
],

My route (no additional Middleware)

Route::post(
  '/auth-request', [
  'uses' => 'UserController@post_authenticateRequest',
  'as' => 'authrequest'
]);

The EncryptCookies class in Kernel.php doesn't seem to have any effect in the AJAX post request - but only for the session part. When I manually add a cookie like

response("OK", 200)->cookie("mysession", Session::getId(), 60);

it is encrypted!

When I completely remove EncryptCookies in Kernel.php for both "api" and "web" the created session from the AJAX request is loaded correctly - but without encryption anymore.

How do I get the AJAX session cookie beeing encrypted? Do I need any other Middleware?

Thanks for your help.

回答1:

After reading the comment from lagbox, I've tried several places for the EncryptCookies::class definition in my "api" part. I need to place it not only before StartSession but as the first element. And now it works!

My complete $middlewareGroups part in Kernel.php now looks like this:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\App::class,
    ],

    'api' => [
        \App\Http\Middleware\EncryptCookies::class,
        'throttle:60,1',
        'bindings',
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    ],
];

Hope this is helpfull.