简体   繁体   中英

Laravel auth::login in EventListener doesn't persist

I have a Laravel 5.2 app where I'm trying to login a user in an Event Listener. All routes are wrapped in web middleware, I'm using database for the session and I see it creates an entry when the event listener executes, however accessing other pages later behave as if there's no user in session.

Just to test out my code, I added the same listener code in a controller route and that works, it persists. I'm suspecting this has to do with the web middleware not being available to an event listener. I've tried handling the event in a controller, same behaviour.

I've noticed the user_id in the sessions DB table is set to null when logging in from the event listener, but it has the right value when logging in from the controller. I'm not sure why this is or how to change it (explicitly setting the user_id field before logging in has no effect)

Additionally, calling Auth::user() immediately in the event listener after the login returns a valid user ! It's just not available to the rest of the application. I'm suspecting this is because the plugin that fires the event is in a separate mini-application, as seen by the routes. Wrapping it in the same middleware also has no effect.

What do I have to do to get the event listener login to persist across the app ?

// EventListener, doesn't persist
public function handle(Saml2LoginEvent $event)
{
    $user = $event->getSaml2User();
    $laravelUser = User::where('mail', $user->getAttributes()['mail'][0])->where('active', 1)->first() ;
    Auth::guard('web')->login($laravelUser);
}

// UserController, persists !
public function home(Request $request){
    $laravelUser = User::where('mail', 'test@mail.com')->where('active', 1)->first() ;
    Auth::guard('web')->login($laravelUser);
}

The event listener class needs to be part of the web middleware to have access to session persistence. So adding those classes to the web middleware group solves the problem

Auth::login($user) was not working for me even after trying everything. (Added saml middlewares, etc).

It worked for me after removing all dump(), var_dump(), die(), etc. from the Listener!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM