11

This is my first attempt at a laravel package and have run into an issue where Auth::attempt($credentials) works within my login controller, but upon redirection to a protected route or controller, the user is no longer authenticated. Below is my login controller method with the redirect to dashboard commented out.

public function attempt(Request $request){

    $email =  strtolower(strip_tags(htmlspecialchars($request->input('email'))));
    $password = strip_tags(htmlspecialchars($request->input('password')));

    if (Auth::attempt(array('email' => $email, 'password' => $password)))
    {
        // Redirect to dashboard route
        //return redirect()->intended('/admin');
        if(Auth::check())
            print_r(Auth::user());
    }
}

A response to valid credentials prints out the correct user record and Auth::check returns true. But, when redirected to the admin controller, the user is not authenticated. Below is the admin controller method that should output the authenticated user, but only returns "not logged".

public function index()
{
    if(Auth::check()) print_r(Auth::user());
    else echo "not logged";
}

Both controllers use Auth;, their namespaces are consistent with vendor/package/pathToDir, db is setup correctly, and the encryption key has been set. Any ideas on what's going wrong? Thanks

Will
  • 383
  • 3
  • 12

2 Answers2

27

Turns out the issue was with the new web middleware, moved all my routes that require session data in to the route group and everything works as normal.

Route::group(['middleware' => ['web']], function () {

    Route::get("/login", ['uses'=>'SiteLogin@index']);
    Route::post("/login", ['uses'=>'SiteLogin@attempt']);
    Route::get("/logout", ['uses'=>'SiteLogin@logout']);

    Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function () {
        Route::get('/', ['uses'=>'Admin@index']);
    });
});
Will
  • 383
  • 3
  • 12
  • 3
    You saved my day! It turns out, for default routes within `routes/web.php` Laravel applies whole middleware group called "web". And doesn't apply this group to external package routes loaded via service provider's method `$this->loadRoutesFrom(__DIR__.'/routes.php');` – Evgeniy Maynagashev Feb 27 '17 at 14:03
  • Saved me a lot of time as I was trying to achieve somthing similar with my package, thanks :) How did you end up figuring this out/troubleshooting it? @Will – logikurl Mar 05 '20 at 12:17
0

The default behavior of the method attempt is to not keep the user logged.

You should change it to:

if (Auth::attempt(array('email' => $email, 'password' => $password), false, true))

This way you will set remember as false and login as true.

Check more about this here: https://laravel.com/docs/5.2/authentication

Laerte
  • 7,013
  • 3
  • 32
  • 50