auth() method null on Exceptions

2019-07-24 05:00发布

问题:

I was playing around with Laravel 5.4.23 and i came across this scenario when i hit a 404 page the auth(), auth()->check(), auth()->user(), and those are not initialized thus returning null in views, or anywhere near that.

i even went to AppServiceProvider.php class to do some tests,

dd(auth()->check());

returns Null in the boot method, even if i'm logged in, which makes 0 sense to me.

that means, whenever a users hits a 404 page, navbars and so on will not render the user data like for instance, traditionally we have the user profile button on top right side in navbar like here on stackoverflow, in that case in Laravel, this is not possible with what i'm seeing.

Am i on the right track or am i missing something ?

it appears to me that Laravel attempts to log the user in after completing the requests i tests.

hope i find the answer here.

Thanks.

UPDATE:

including a manual login attempt in the boot method in App\Providers\AppServiceProvider seemed to fix the null issue in the aut() commands, but i believe this will attempt to log the user in twice per page request, since obviously Laravel is getting the logged in user after the boot, exceptions requests and dunno what else.

回答1:

This happens because the session gets initialised by the web middleware group. When a route is not found the middleware never gets initialised. Therefore the application fails to find the authenticated user from the session.

There's a workaround for this though. Moving the session and cookie middleware from the web middleware group to the global middleware seems to fix this. But the downside is that every single route in your application with have sessions and cookies enabled by default. This can be problematic if you have api routes.

MOVE (don't copy) these routes from web middleware group ($middlewareGroups) to the global middleware list ($middleware).

\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,

You can skip the EncryptCookies middleware if you don't want to detect users using their remember_token in your error pages.