33

I have found many resources online with similar issues but none of the solutions appear to solve my problem.

When I log a user in with the following code, everything seems fine:

$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email' => $email, 'password' => $password))) {
    return Auth::user();
} else {
    return Response::make("Invalid login credentials, please try again.", 401);
}

The Auth::attempt() function returns true and the logged in user is returned to the client using Auth::user().

But if the client makes another request to the server directly after, Auth::user() returns NULL.

I have confirmed that Laravel sessions are working correctly by using the Session::put() and Session::get() successfully.

Update

On further investigation it appears that sessions are not persisting either! Could this be something to do with having the AngularJS web app server via app.mydomain.com and the Laravel API being served via api.mydomain.com?

My User model is as follows:

<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password');

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->password;
    }

    /**
     * Get the e-mail address where password reminders are sent.
     *
     * @return string
     */
    public function getReminderEmail()
    {
        return $this->email;
    }

}

My auth config is as follows:

<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Default Authentication Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the authentication driver that will be utilized.
    | This driver manages the retrieval and authentication of the users
    | attempting to get access to protected areas of your application.
    |
    | Supported: "database", "eloquent"
    |
    */

    'driver' => 'eloquent',

    /*
    |--------------------------------------------------------------------------
    | Authentication Model
    |--------------------------------------------------------------------------
    |
    | When using the "Eloquent" authentication driver, we need to know which
    | Eloquent model should be used to retrieve your users. Of course, it
    | is often just the "User" model but you may use whatever you like.
    |
    */

    'model' => 'User',

    /*
    |--------------------------------------------------------------------------
    | Authentication Table
    |--------------------------------------------------------------------------
    |
    | When using the "Database" authentication driver, we need to know which
    | table should be used to retrieve your users. We have chosen a basic
    | default value but you may easily change it to any table you like.
    |
    */

    'table' => 'users',

    /*
    |--------------------------------------------------------------------------
    | Password Reminder Settings
    |--------------------------------------------------------------------------
    |
    | Here you may set the settings for password reminders, including a view
    | that should be used as your password reminder e-mail. You will also
    | be able to set the name of the table that holds the reset tokens.
    |
    | The "expire" time is the number of minutes that the reminder should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'reminder' => array(

        'email' => 'emails.auth.reminder',

        'table' => 'password_reminders',

        'expire' => 60,

    ),

);

The migration used to create the users table is as follows:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('first_name');
            $table->string('last_name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function(Blueprint $table)
        {
            //
        });
    }

}

And the session config:

<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Default Session Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the default session "driver" that will be used on
    | requests. By default, we will use the lightweight native driver but
    | you may specify any of the other wonderful drivers provided here.
    |
    | Supported: "file", "cookie", "database", "apc",
    |            "memcached", "redis", "array"
    |
    */

    'driver' => 'database',

    /*
    |--------------------------------------------------------------------------
    | Session Lifetime
    |--------------------------------------------------------------------------
    |
    | Here you may specify the number of minutes that you wish the session
    | to be allowed to remain idle before it expires. If you want them
    | to immediately expire on the browser closing, set that option.
    |
    */

    'lifetime' => 120,

    'expire_on_close' => false,

    /*
    |--------------------------------------------------------------------------
    | Session File Location
    |--------------------------------------------------------------------------
    |
    | When using the native session driver, we need a location where session
    | files may be stored. A default has been set for you but a different
    | location may be specified. This is only needed for file sessions.
    |
    */

    'files' => storage_path().'/sessions',

    /*
    |--------------------------------------------------------------------------
    | Session Database Connection
    |--------------------------------------------------------------------------
    |
    | When using the "database" or "redis" session drivers, you may specify a
    | connection that should be used to manage these sessions. This should
    | correspond to a connection in your database configuration options.
    |
    */

    'connection' => null,

    /*
    |--------------------------------------------------------------------------
    | Session Database Table
    |--------------------------------------------------------------------------
    |
    | When using the "database" session driver, you may specify the table we
    | should use to manage the sessions. Of course, a sensible default is
    | provided for you; however, you are free to change this as needed.
    |
    */

    'table' => 'sessions',

    /*
    |--------------------------------------------------------------------------
    | Session Sweeping Lottery
    |--------------------------------------------------------------------------
    |
    | Some session drivers must manually sweep their storage location to get
    | rid of old sessions from storage. Here are the chances that it will
    | happen on a given request. By default, the odds are 2 out of 100.
    |
    */

    'lottery' => array(2, 100),

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Name
    |--------------------------------------------------------------------------
    |
    | Here you may change the name of the cookie used to identify a session
    | instance by ID. The name specified here will get used every time a
    | new session cookie is created by the framework for every driver.
    |
    */

    'cookie' => 'laravel_session',

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Path
    |--------------------------------------------------------------------------
    |
    | The session cookie path determines the path for which the cookie will
    | be regarded as available. Typically, this will be the root path of
    | your application but you are free to change this when necessary.
    |
    */

    'path' => '/',

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Domain
    |--------------------------------------------------------------------------
    |
    | Here you may change the domain of the cookie used to identify a session
    | in your application. This will determine which domains the cookie is
    | available to in your application. A sensible default has been set.
    |
    */

    'domain' => null,

    /*
    |--------------------------------------------------------------------------
    | HTTPS Only Cookies
    |--------------------------------------------------------------------------
    |
    | By setting this option to true, session cookies will only be sent back
    | to the server if the browser has a HTTPS connection. This will keep
    | the cookie from being sent to you if it can not be done securely.
    |
    */

    'secure' => false,

);

Any ideas?

Community
  • 1
  • 1
Leon Revill
  • 1,950
  • 3
  • 18
  • 25
  • can you show the route(s) you are doing before and after auth? Also, does Auth::check() return false? – warspite Feb 06 '14 at 13:50
  • Auth::check() returns null. The route doesn't make a difference same result anywhere. Thanks for you're time. – Leon Revill Feb 06 '14 at 16:38
  • Also check your `app/config/session.php` settings. – The Alpha Feb 06 '14 at 18:19
  • General Session::put/get is working fine so the session settings must be working. Thanks. – Leon Revill Feb 06 '14 at 18:22
  • I can confirm that the sessions table is being populate with login and every time the client makes a call to the Laravel API, is that correct? – Leon Revill Feb 07 '14 at 07:14
  • I'm currently having this same issue. Tried all the suggestions in this and related questions, but to no avail. Has anyone found a definite explanation for what's going on? I'm using Laravel 4.2.11 (incidentally I have an older app where I did get this to work, the only significant difference I found between the two is the older one is Laravel 4.2.8). – PeterG Oct 11 '14 at 02:07
  • Dude, after `Auth::attemp` or `Auth::login()` dont use `echo, var_dump or dd()` i dont know why but those prevent to save the session in the browser, check this answer http://stackoverflow.com/a/39008752/5708097 – Rolly Aug 18 '16 at 01:46

11 Answers11

34

I had this problem. Changing primary key for user model helped for me.

Try to add something like

protected $primaryKey = 'user_id';

in class User{} (app/models/User.php)

(Field user_id is auto increment key in my Schema for 'users' table)

See also this ticket: https://github.com/laravel/framework/issues/161

Juljan
  • 2,391
  • 1
  • 17
  • 20
  • 2
    2 hours lost trying to figure out why the sessions where not working until i realised i didn't have a standard id key in the user table. It may not have been the solution to this question but this helped me – Chris Mccabe Jun 05 '14 at 13:06
  • 2
    This worked. I added following: protected $primaryKey = 'id'; in users model – codeomascot Jan 24 '15 at 07:05
  • In my case, after doing so, I can't login :( – Miron Aug 16 '16 at 09:55
  • ah its working, the problem is, i set the primary key to username... i fixed the problem by making new column, and set the primary key as integer auto increment... THANKYOU! – NoobnSad Feb 11 '20 at 03:31
20

I had the same issue in laravel 5.7. Whoever facing similar issues if session not persisting after authentication , can follow the solution like below..

Open file App\Http\kernel.php

Move \Illuminate\Session\Middleware\StartSession::class, from protected $middlewareGroups to protected $middleware . That's it.

Nayeem Azad
  • 657
  • 5
  • 20
14

I had this problem today morning, and I realized that when you output data before calling

Auth::attempt($credentials);

Then you can BE SURE THAT YOUR SESSION WILL NOT BE SET. So for example if you do something like

echo "This is the user " . $user;

just above the line that says

Auth::attempt($credentials); 

Then rest assured that you will spend the whole morning trying to find why laravel is not persisting the authenticated user and calling

Auth::user()

will give you a null, and also calling

Auth::check() 

will always give you false.

This was my problem and that is how I fixed it, by removing the echo statement.

Moses Ndeda
  • 453
  • 5
  • 11
  • 3
    Thnks man, you made my day! I want to add that if you print something not only before, but and after - you will have the same issue. I stumble when try to create ajax auth with json_encode print result. – d7p4x Aug 18 '15 at 09:44
  • **Set-Cookie** HTTP header do not seems to be set when output is sent. – Xartrick Dec 27 '17 at 03:49
5

You can pass true to Auth:attempt() for the remember parameter:

if ( Auth::attempt(array('email' => $email, 'password' => $password), true) ) {
    return Auth::user();
} else {
    return Response::make("Invalid login credentials, please try again.", 401);
}
TonyArra
  • 10,607
  • 1
  • 30
  • 46
  • Thanks. I've tried that but it still doesn't persist. I'm returning it so the client can store the user inba cookie. – Leon Revill Feb 06 '14 at 18:51
  • @LeonRevill but you shouldn't be doing that yourself. The Auth::attempt() does this for you (if authentication is successful). You should normally be returning a redirect to a route upon successful authentication. – TonyArra Feb 06 '14 at 19:12
  • Its a restful API so a redirect would be useless. Any idea why the login doesnt persist though? Its driving me mad. Thanks – Leon Revill Feb 06 '14 at 19:28
4

Firstly, I have the same problem on Laravel 5.8.

I confirm that the solution of @nayeem-azad is the good one, at least in my case. One difference, in App\Http\kernel.php, I do not moved this line :

\Illuminate\Session\Middleware\StartSession::class

from protected $middlewareGroups to protected $middleware but only copied it to protected $middleware.

Hope it helps ;-)

HappyToDev
  • 94
  • 6
2

I was having a similar issue, and in the end I was so focused on the back-end that I didn't consider the problem could be on the front-end.

I'd used blade to output Auth:logout() directly to the front end to create a logout button, like so:

<a href="{{Auth::logout()}}">Log out</a>

Which is incorrect. Each time I logged into the application, I would be directed to a page with this button on, which I mistakenly thought would call Auth::logout() when pressed. Of course, the PHP is rendered on pageload and Auth::logout() is called straight away. Then when a user navigates to another page, since they've been logged out they're redirected to the login page to start the process again.

FYI - The correct way to create a logout button, if you're using the default Auth route controller would be to direct to the route '/auth/logout', like so:

<a href="{{url('/auth/logout')}}">Log Out</a>

TimothyBuktu
  • 2,016
  • 5
  • 21
  • 35
0

The issue might be with your session configuration. Check to see if you've set up the session table Laravel needs to use the 'database' driver.

You can see the config here: http://laravel.com/docs/session#database-sessions

Hope this helps!

Bill Riley
  • 97
  • 1
  • 9
0

How long is the id field in your sessions table? Laravel uses a sha1 hash as the session id, which yields a string of length 40. I had a similar problem and it was because my id field was set to length 32.

See this question: Laravel 4.1 authentication session data not persisting across requests

Community
  • 1
  • 1
ralbatross
  • 2,448
  • 4
  • 25
  • 45
0

Okay I haven't dug deep into it, but i've figured that laravel only returns cookies over a secure connection.

As you must have noticed, laravel is setting up a cookie but it is not responding to the lifetime setting in session.php

/*
    |--------------------------------------------------------------------------
    | Session Lifetime
    |--------------------------------------------------------------------------
    |
    | Here you may specify the number of minutes that you wish the session
    | to be allowed to remain idle before it expires. If you want them
    | to immediately expire when the browser closes, set it to zero.
    |
    */

    'lifetime' => 60*24*30, //doesn't seem to work ?

To get this to work on your local server you must mimic a https connection to ensure that the login persists. You can do this by generating a fake ssl certificate/key for your local domain.

There are several tutorials available online that can help you enable ssl.

These might be useful :

How to enable SSL in MAMP Pro

MAMP with SSL (https)

How To Create a SSL Certificate on Apache for Ubuntu 12.04

Varun Nath
  • 5,570
  • 3
  • 23
  • 39
0

Try to use

ob_start();
ob_flush(); 

before the return or the echo statment;

ex:

public function login() {

        PogfixHelper::$return['ret'] = "error";
        $iten = array(
            'email' => Input::get("Mail"),
            'password' => Input::get("Password"),
            'flag_ativo' => 1
        );

        if (Auth::attempt($iten)) {
            PogfixHelper::$return['ret'] = "ok";
            PogfixHelper::$return['okMsg'] = "U are in";
            PogfixHelper::$return['redirect'] = URL::to('panel/calendar');
        } else {
            PogfixHelper::$return['errorMsg'] = "Password not match";
        }
        ob_start();
        ob_flush();
        echo json_encode(PogfixHelper::$return);
    }
0

Using Laravel 5.7 by the way.

I had the same problem but it was because I was trying to use their username for logging in. In the case you have custom user data besides the default email, name, and password and you don't want them to login via their email then you go to vendor/laravel/framework/src/Illuminate/Foundation/Auth/ and open the AuthenticatesUsers.php file. In it there's a public function called username:

     /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'email'; // <----
    }

As you can see, by default it's set to 'email'. You can then change this to what you want the user to login with in combination with their password. So for my website I wanted the user to login using their username. So you simply change it from 'email' to 'username'.

I hope this helps someone.

NOTE: Peculiarly enough, for whatever reason, it gave me no errors when I tried to log in using username and password. Instead, it would seemingly validate but just not persist the user and I have no idea why.