Thursday, May 17, 2018

Auth0 - Laravel - Database sessions

I've decided to start a side project--an order management system for a very specific and niche industry--and I decided the project was a great candidate for Laravel. Since I'm partial to Auth0 as an IdP, I decided to wire Auth0 up to my site and use the callback and API available in the Laravel Quickstart for Auth0. As there are copious examples of hooking the two up, I figured I'd be in and done within the hour. For the most part, that was true. If you've used Auth0, it's straightforward to add a client and the examples move you right along.

But the out-of-the-box Laravel defaults to file-based sessions. Not ideal in a world of autoscaling EC2 clusters and ELBs. It's easy to coax Laravel into using database sessions (or redis, this should apply) with two steps

  • change SESSION_DRIVER=file to SESSION_DRIVER=database in your .env,
  • run php artisan session:table to add a migration script.

OK, fine... three steps: run php artisan migrate to take care of generating the table.

In the spirit of nothing's ever easy, session state was not surviving a page reload. I'd log in via the lovely Auth0 hosted page, the callback returned to the appropriate page on my site, but when that page redirected to my home page, Auth::user() was null and the page guard sent me back to the login screen.

I started digging around in the LaravelSessionStore code the Auth0 API was using. Everything looked good. New sessions were being created with good session payloads, but the sessions were unavailable as soon as the page reloaded. I noticed the sessions table has a user_id column which was always NULL, even if the payload was populated with the auth0_user settings. Checking the default implementation of the sessions table, I noticed the type: integer. Auth0, as you know, uses a string identifier in the form of auth0|xxx...zzz. I changed the definition, rolled back the database, migrated and reloaded the page. Viola. Sessions writing with a user_id and session state working as expected.

The code follows.

No comments:

Post a Comment