php Laravel Auth:attempt() 不会持续登录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21603347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:16:55  来源:igfitidea点击:

Laravel Auth:attempt() will not persist login

phpauthenticationlaravellaravel-4

提问by Leon Revill

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 trueand the logged in user is returned to the client using Auth::user().

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

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

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

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

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

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?

在进一步调查中,会话似乎也没有持续存在!这可能与通过 app.mydomain.com 拥有 AngularJS Web 应用程序服务器以及通过 api.mydomain.com 提供 Laravel API 有关吗?

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 userstable is as follows:

用于创建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)
        {
            //
        });
    }

}

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?

有任何想法吗?

回答by Juljan

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)

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

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

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

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

另见这张票:https: //github.com/laravel/framework/issues/161

回答by Moses Ndeda

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

然后请放心,您将花费一整个上午的时间来找出为什么 laravel 没有持久化经过身份验证的用户并调用

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.

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

回答by Nayeem Azad

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..

我在 Laravel 5.7 中遇到了同样的问题。如果会话在身份验证后不持久,则面临类似问题的任何人都可以按照如下解决方案进行操作。

Open file App\Http\kernel.php

打开文件 App\Http\kernel.php

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

\Illuminate\Session\Middleware\StartSession::class,从移动protected $middlewareGroupsprotected $middleware。就是这样。

回答by TonyArra

Try passing trueto Auth:attempt() for the rememberparameter:

尝试将参数传递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);
}

I'm not sure why you're returning Auth::user() at all though.

我不知道你为什么要返回 Auth::user() 。

回答by TimothyBuktu

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:

我使用刀片Auth:logout()直接输出到前端来创建一个注销按钮,如下所示:

<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.

这是不正确的。每次我登录应用程序时,我都会被引导到一个带有此按钮的页面,我错误地认为Auth::logout()按下时会调用它。当然,PHP 在页面加载时呈现并立即Auth::logout()被调用。然后,当用户导航到另一个页面时,由于他们已被注销,他们将被重定向到登录页面以再次启动该过程。

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:

仅供参考 - 创建注销按钮的正确方法,如果您使用默认的 Auth 路由控制器,将指向路由“/auth/logout”,如下所示:

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

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

回答by f-red

Firstly, I have the same problem on Laravel 5.8.

首先,我在 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 :

我确认@nayeem-azad 的解决方案是好的,至少在我的情况下是这样。一个区别,在App\Http\kernel.php 中,我没有移动这一行:

\Illuminate\Session\Middleware\StartSession::class

from protected $middlewareGroupsto protected $middlewarebut only copied it to protected $middleware.

受保护的 $middlewareGroups受保护的 $middleware但只将其复制到受保护的 $middleware

Hope it helps ;-)

希望能帮助到你 ;-)

回答by Edward Severinsen

Using Laravel 5.7 by the way.

顺便说一下,使用 Laravel 5.7。

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 passwordand you don't want them to login via their emailthen you go to vendor/laravel/framework/src/Illuminate/Foundation/Auth/and open the AuthenticatesUsers.phpfile. In it there's a public function called username:

我有同样的问题,但它是因为我试图用自己的用户名登录。在这种情况下,你有除了默认的自定义用户数据emailnamepassword你不通过他们他们想登录email,然后你去vendor/laravel/framework/src/Illuminate/Foundation/Auth/和打开AuthenticatesUsers.php文件。其中有一个名为 的公共函数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'.

如您所见,默认情况下它设置为'email'. 然后,您可以将其更改为您希望用户与其密码一起登录的内容。所以对于我的网站,我希望用户使用他们的username. 因此,您只需将其从 更改'email''username'

I hope this helps someone.

我希望这可以帮助别人。

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

注意:很奇怪,无论出于何种原因,当我尝试使用username和登录时,它没有给我任何错误password。相反,它似乎会验证但不会持久化用户,我不知道为什么。

回答by Jean Dobler

Try to use

尝试使用

ob_start();
ob_flush(); 

before the return or the echo statment;

在 return 或 echo 语句之前;

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

回答by Bill Riley

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.

问题可能与您的会话配置有关。检查您是否已经设置了 Laravel 需要使用“数据库”驱动程序的会话表。

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

您可以在此处查看配置:http: //laravel.com/docs/session#database-sessions

Hope this helps!

希望这可以帮助!

回答by ralbatross

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.

会话表中的 id 字段有多长?Laravel 使用 sha1 哈希作为会话 id,它产生一个长度为 40 的字符串。我遇到了类似的问题,这是因为我的 id 字段设置为长度 32。

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

看到这个问题:Laravel 4.1 authentication session data not persisting across requests