Home » Php » php – Laravel's CSRF token and load balancing

php – Laravel's CSRF token and load balancing

Posted by: admin July 12, 2020 Leave a comment

Questions:

Consider this scenario:

An application has a login route that is protected by Laravel’s CSRF filter:

Route::group(array('before' => 'csrf'), function() {

    Route::post('/doLogin', array('as' => 'doLogin', 'uses' => '[email protected]'));

});

The application sits behind a load balancer, where each request is doled out randomly to either server01 or server02. Laravel is configured to persist sessions in a database, which is shared by both server01 and server02. The standard path to follow is: a user accesses /, enters their credentials into a login form, and submits those credentials to /doLogin, which checks the token, processes the credentials, and returns the user to / on error, or /home on success.

My question is this: since there’s no guarantee that a user who accesses / on server01 will post to /doLogin on server01, will Laravel’s built-in CSRF tokens work? Or since the token is stored in Session, will it work regardless of which server ends up being assigned by the LB?

How to&Answers:

CSRF will work regardless of which server it hits if session is shared between these servers.

Database, Cookie and memcached/redis session drivers are good.

File session driver should not work ususally.

CSRF token from client is compared with the one in the session.

Answer:

You should use cookie or database driver for session handling .

for more info read laravel session doc .