Laravel Auth:attempt()不会持久登录

Leo*_*ill 28 php authentication laravel laravel-4

我在网上找到了许多类似问题的资源,但没有一个解决方案可以解决我的问题.

当我使用以下代码登录用户时,一切似乎都很好:

$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);
}
Run Code Online (Sandbox Code Playgroud)

Auth::attempt()函数返回true并使用登录用户返回给客户端Auth::user().

但是如果客户端直接向服务器发出另一个请求,则Auth::user()返回NULL.

我已经确认Laravel会话通过使用Session::put()Session::get()成功正常工作.

更新

在进一步的调查中,似乎会议也没有坚持!这可能与通过app.mydomain.com获得AngularJS Web应用服务器以及通过api.mydomain.com提供的Laravel API有关吗?

我的用户模型如下:

<?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;
    }

}
Run Code Online (Sandbox Code Playgroud)

我的auth配置如下:

<?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,

    ),

);
Run Code Online (Sandbox Code Playgroud)

用于创建users表的迁移如下:

<?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)
        {
            //
        });
    }

}
Run Code Online (Sandbox Code Playgroud)

并且会话配置:

<?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,

);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Jul*_*jan 29

我有这个问题.更改用户模型的主键对我有帮助.

尝试添加类似的东西

protected $primaryKey = 'user_id';
Run Code Online (Sandbox Code Playgroud)

在类User {}(app/models/User.php)中

(字段user_id是我的"用户"表格架构中的自动增量键)

另请参见此票证:https://github.com/laravel/framework/issues/161

  • 在我意识到我没有在用户表中有一个标准的id密钥时,试图弄清楚为什么会话不工作的2个小时.它可能不是这个问题的解决方案,但这对我有帮助 (2认同)
  • 这很有效.我添加了以下内容:protected $ primaryKey ='id'; 在用户模型中 (2认同)

Mos*_*eda 13

我今天早上遇到了这个问题,我意识到在你打电话之前输出数据

Auth::attempt($credentials);
Run Code Online (Sandbox Code Playgroud)

那么你可以确定你的会话不会被设置.例如,如果你做了类似的事情

echo "This is the user " . $user;
Run Code Online (Sandbox Code Playgroud)

就在那条线上方

Auth::attempt($credentials); 
Run Code Online (Sandbox Code Playgroud)

然后请放心,您将花费整个上午试图找到为什么laravel不会保持经过身份验证的用户并致电

Auth::user()
Run Code Online (Sandbox Code Playgroud)

会给你一个null,并且还会调用

Auth::check() 
Run Code Online (Sandbox Code Playgroud)

永远都会给你假的.

这是我的问题,这就是我通过删除echo语句修复它的方法.

  • 哎呀,你让我开心!我要补充一点,如果您不仅在打印之前而且在打印之后打印某些内容,那么您将遇到同样的问题。当尝试使用json_encode打印结果创建ajax auth时,我迷迷糊糊。 (3认同)

Nay*_*zad 8

我在laravel 5.7中遇到了同样的问题。如果会话在身份验证后仍然存在,则遇到类似问题的人可以遵循以下解决方案。

打开文件 App\Http\kernel.php

移动\Illuminate\Session\Middleware\StartSession::class,protected $middlewareGroupsprotected $middleware。而已。


Ton*_*rra 5

您可以传递true给 Auth:attempt() 参数remember

if ( Auth::attempt(array('email' => $email, 'password' => $password), true) ) {
    return Auth::user();
} else {
    return Response::make("Invalid login credentials, please try again.", 401);
}
Run Code Online (Sandbox Code Playgroud)