19

I have two (but let's image more) micro-services (API) which need to be aware of authenticated user. Ideally I would simple like to resume their sessions.

All micro-services are using same storage for sessions: redis.

All API calls will have Cookie header, so all services will be able to resume sessions based on that cookie. I have successfully implemented this via PHP $_SESSIONs.

Now the question: how would you go about implementing this with Laravel/Lumen?

rummykhan
  • 2,603
  • 3
  • 18
  • 35
rock3t
  • 2,193
  • 2
  • 19
  • 24
  • 2
    Too broad, primarily opinion-based question. There are many ways to do that. For example, using a "cache server" for session storage, like redis. – Frondor Nov 01 '17 at 08:43
  • are you using any API Gateway for authentication or you haven't started implementation. ? – rummykhan Nov 01 '17 at 09:03
  • I recently worked on Microservices, We were using Kong as our API Gateway to attach auth headers, and then each MicroService will receive these details and will get a user either from Redis or any db – rummykhan Nov 01 '17 at 09:05
  • @rummykhan considering AWS API Gateway. My concerns are the fact that Laravel has session and Lumen has not. – rock3t Nov 01 '17 at 09:15
  • @rock3t, I totally respect your opinion but why do you need sessions at all in microservice, I'm still lost. – rummykhan Nov 01 '17 at 09:19
  • But even if you do, You can still use php native sessions. – rummykhan Nov 01 '17 at 09:22
  • @rummykhan you right, there's a reason why Lumen has no session and token based authentication. I was still interested to see if anyone will come forward with suggestion. As far as my implementation goes it's Cokkie header and resuming native PHP $_SESSIONs. I was mainly interested to see if some one came up with Middleware or any other solution to cover this use-case. – rock3t Nov 01 '17 at 09:57
  • @rock3t, I'm glad you asked. I was also thinking of enabling these for lumen, I'm testing it and I'll post as answer if it succeeded or not. – rummykhan Nov 01 '17 at 10:01
  • Well I've tried, You cannot use `illuminate/session` in lumen 5.2 and after, because now some classes in `illuminate/session` depends on `Illuminate/Foundation/Application` and not on `Illuminate/Contracts/Container` which is making them un-usable for lumen. – rummykhan Nov 01 '17 at 10:21
  • Your question is legit, I've upvoted it. – rummykhan Nov 01 '17 at 10:22
  • Thanks @rummykhan for giving it a go. I'll probably will authenticate API calls via tokens for now and then see where projects takes me. Plain PHP $_SESSION are always an option. Put an answer together with your research and PHP nataive SESSIONS and I'll chose it. – rock3t Nov 01 '17 at 11:56
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/157993/discussion-between-rummykhan-and-rock3t). – rummykhan Nov 01 '17 at 12:42
  • The following link is the life saver. [here](http://blog.tegimus.com/2018/08/09/add-session-and-csrf-protection-to-lumen-application/#comment-2) – HexaCrop Nov 30 '18 at 09:12

4 Answers4

72

Last update on 5th of March 2021

(This answer was getting a lot of attention from Laravel community so I thought of updating it.)

Laravel has officially stopped supporting sessions & views in laravel/lumen framework from version 5.2 and on wards.

But laravel still have a component illuminate/session which can be installed in lumen/framework and we can play around with this.

Step - 1

install illuminate/session using

composer require illuminate/session

Step - 2

Now goto bootstrap/app.php and add this middleware

$app->middleware([
    \Illuminate\Session\Middleware\StartSession::class,
]);

Purpose of adding the above middleware is to start session on every request and save session before serving response.

Step - 3

Now add config/session.php, since it is not present in Lumen by default. You can take session.php from Laravel official repo.

Step - 4

Create framework session storage directory by

mkdir -p storage/framework/sessions

Thanks to DayDream

Step - 5

In bootstrap/app.php add bindings for \Illuminate\Session\SessionManager

$app->singleton(Illuminate\Session\SessionManager::class, function () use ($app) {
    return $app->loadComponent('session', Illuminate\Session\SessionServiceProvider::class, 'session');
});

$app->singleton('session.store', function () use ($app) {
    return $app->loadComponent('session', Illuminate\Session\SessionServiceProvider::class, 'session.store');
});

Thanks to @xxRockOnxx for finding loadComponent method. It takes 3 arguments,

  • first one is config file name. (file should be present in config/ directory)
  • second is ServiceProvider FQN
  • third is return of this method.

loadComponent just calls the $app->register and inject $app while building the ServiceProvider

How to Use


// Save Session
$router->get('/', function (\Illuminate\Http\Request $request) {

    $request->session()->put('name', 'Lumen-Session');

    return response()->json([
        'session.name' => $request->session()->get('name')
    ]);
});


// Test session
$router->get('/session', function (\Illuminate\Http\Request $request) {

    return response()->json([
        'session.name' => $request->session()->get('name'),
    ]);
});

I've also added example over github supporting from lumen framework v5.6 to all the way to current version v8.0.

https://github.com/rummykhan/lumen-session-example

rummykhan
  • 2,603
  • 3
  • 18
  • 35
  • 3
    Thank you so much. This was very helpful – Ahmed Shefeer Aug 04 '18 at 08:35
  • 2
    However the Redirector (for example when using redirect()) session does not get set, it is always null. I can see the session object set on Request object so I am able to use view()->with() properly but if i use redirect()->with() it fails due to session object being null on the redirector – Ahmed Shefeer Aug 04 '18 at 08:37
  • when i do that i get : Session store not set on request. – Tarek Dec 07 '19 at 10:42
  • On Step 4, you'll probably want to add a `.gitignore` file - https://github.com/laravel/laravel/blob/8.x/storage/framework/sessions/.gitignore – shanecp Mar 12 '21 at 04:25
  • it is creating session for every new request and i can check my sessions dir it has lot of files generated. is it not causing the memory issue after some days/months time..? – Rahul Dhande Mar 26 '21 at 05:42
6

It is important to that you also use $request->session(), otherwise it will not work.

Kevin Upton
  • 3,336
  • 2
  • 21
  • 24
4

I tried the solution mentioned above, however, it's also required to create a folder storage/framework/sessions if using the default settings.

Daydream
  • 41
  • 3
2

The accepted answer is outdated.

I answered and explained a bit how to properly do it in my answer on this question

I also posted what is the problem on my question at Laracasts

To quote:

the solution that is found in the link you gave is that, first it tells you to manually register the SessionManager to prevent the unresolvable depedency parameter #0 $app then also register the existing SessionServiceProvider which also binds another instance SessionManager.

Problem with that is, some components use the other instance and other parts use the new one which causes my auth attempt session not being save despite actually being put inside.

Community
  • 1
  • 1
captainskippah
  • 1,350
  • 8
  • 16