如何更改/自定义 Laravel 4 和 Laravel 5 用户身份验证的密码字段名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26073309/
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-09-14 10:11:27  来源:igfitidea点击:

How to change / Custom password field name for Laravel 4 and Laravel 5 user authentication

phpauthenticationlaravellaravel-4laravel-5

提问by Marcin Nabia?ek

I would like to change password field in database when using Laravel authentication. I want my column in userstable has name passwdand not password. I tried to run something like this:

我想在使用 Laravel 身份验证时更改数据库中的密码字段。我希望users表中的列有 namepasswd而不是password。我试图运行这样的东西:

Auth::attempt(array(
    'user_name' => 'admin',
    'passwd' => 'hardpass',
));

but it doesn't work.

但它不起作用。

I also tried to add in Usermodel the following function:

我还尝试在User模型中添加以下功能:

public function getAuthPassword() {
    return $this->passwd;
}

but it also changes nothing. User is still not being authenticated. Is it possible in Laravel to change password field name in database ?

但它也没有任何改变。用户仍未通过身份验证。在 Laravel 中是否可以更改数据库中的密码字段名称?

回答by Marcin Nabia?ek

Information

信息

You can change easy all other fields in database and use them for authentication. The only problem is with passwordfield.

您可以轻松更改数据库中的所有其他字段并将其用于身份验证。唯一的问题是password字段。

In fact passwordfield is in some way hard coded in Laravel (but not the way many think) so you cannot just pass array as you passed in your question.

事实上,password字段在 Laravel 中以某种方式硬编码(但不是许多人认为的方式),因此您不能在传递问题时只传递数组。

By default if you pass array to attempt(and probably other Auth functions like validateor once) if you do it this way:

默认情况下,如果您将数组传递给attempt(可能还有其他 Auth 函数,例如validateonce),如果您这样做:

Auth::attempt(array(
    'user_name' => 'admin',
    'password' => 'hardpass',
));

default Eloquent driver will run the following query:

默认的 Eloquent 驱动程序将运行以下查询:

select * from `users` where `user_name` = 'admin' limit 1;

After getting this data from database it will compare password you gave with password property for User object that was created.

从数据库中获取此数据后,它会将您提供的密码与创建的用户对象的密码属性进行比较。

But if you simply use:

但如果你只是使用:

Auth::attempt(array(
    'user_name' => 'admin',
    'passwd' => 'hardpass',
));

the following query will be run:

将运行以下查询:

select * from `users` where `user_name` = 'admin' and `passwd` = 'hardpass' limit 1;

and no user will be found in database (in passwdyou store hashed password). This is because Eloquent removes from query passwordbut use any other data to run query. Also if you try here to use 'passwd' => Hash:make($data['password'])although user will be found, comparing password won't work.

并且不会在数据库中找到用户(在passwd您存储散列密码中)。这是因为 Eloquent 从查询中删除password但使用任何其他数据来运行查询。此外,如果您尝试使用此处'passwd' => Hash:make($data['password'])虽然会找到用户,则比较密码将不起作用。

Solution

解决方案

Solution is quite easy. You need to run Auth::attemptlike this:

解决方法很简单。你需要Auth::attempt像这样运行:

Auth::attempt(array(
    'user_name' => 'admin',
    'password' => 'hardpass',
));

As you see you still pass passwordas key (although this column doesn't exits in userstable) because only this way Eloquent driver won't use it for building query.

如您所见,您仍然password作为键传递(尽管此列不会在users表中存在),因为只有这样 Eloquent 驱动程序才不会使用它来构建查询。

Now in Usermodel (app/models/User.php) file you need to add the following function:

现在在User模型 ( app/models/User.php) 文件中,您需要添加以下函数:

public function getAuthPassword() {
    return $this->passwd;
}

As you see you use here the column that really exists in database: passwd.

如您所见,您在这里使用了数据库中真正存在的列:passwd

Using it this way you can have column with password named anything you want and you can still use default Eloquent driver for it.

以这种方式使用它,您可以将带有密码的列命名为您想要的任何名称,并且您仍然可以使用默认的 Eloquent 驱动程序。

Sample data to test

要测试的样本数据

I've created very simple test for it.

我为它创建了非常简单的测试。

You just need to replace your app/routes.phpfile with the following:

您只需要app/routes.php使用以下内容替换您的文件:

Route::get('/', function () {

    if (Auth::check()) {
        echo "I'm logged in as " . Auth::user()->user_name . "<br />";
        echo "<a href='/logout'>Log out</a>";
    } else {
        echo "I'm NOT logged in<br />";


        Auth::attempt(array(
            'user_name' => 'admin',
            'password'  => 'hardpass',
        ));


        if (Auth::check()) {
            echo "Now I'm logged in as " . Auth::user()->user_name . "<br />";
            echo "<a href='/logout'>Log out</a>";
        } else {
            echo "I'm still NOT logged in<br />";
        }
    }


});

Route::get('/logout', function () {
    Auth::logout();
    return "You have been logged out";
});


Route::get('/db', function () {

    if (!Schema::hasTable('users')) {


        Schema::create('users', function ($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('user_name', 60)->unique();
            $table->string('passwd', 256);
            $table->rememberToken();
            $table->timestamps();
        });

        DB::table('users')->insert(
            [
                [
                    'user_name' => 'admin',
                    'passwd'    => Hash::make('hardpass'),
                ]
            ]
        );
    }

    echo "Table users has been created";
});
  1. Create empty database and set connection data in app/config/database.php
  2. Now you can run /dburl for example http://localhost/yourprojectname/dbjust to create users table.
  3. Now you can run /url for example http://localhost/yourprojectname/- as you see user is logged in even if in userstable in database you don't have any passwordcolumn (data for authentication has been passed as strings without any forms but of course in real application you will add them) . You can run this url once more time - as you see user is still logged so it is working as expected.
  4. If you click on Log outlink, you will be logged out
  1. 创建空数据库并在其中设置连接数据 app/config/database.php
  2. 现在您可以运行/dburlhttp://localhost/yourprojectname/db来创建用户表。
  3. 例如,现在您可以运行/url http://localhost/yourprojectname/- 正如您看到的用户已登录,即使users在数据库中的表中您没有任何password列(用于身份验证的数据已作为字符串传递而没有任何形式,但当然在实际应用程序中您将添加它们)。您可以再次运行此 url - 正如您看到的,用户仍处于登录状态,因此它按预期工作。
  4. 如果您点击Log out链接,您将被注销

Laravel 5 changes for above

Laravel 5 对上面的更改

This solution was tested in Larave 4.2.9 (everything as above) and also in Laravel 5. In Laravel5 everything works the same but you need of course edit files in different paths:

该解决方案已在 Larave 4.2.9(如上)和 Laravel 5 中进行了测试。在 Laravel5 中,一切都相同,但您当然需要在不同路径中编辑文件:

  1. Usermodel is in app/User.phpfile
  2. routes are in app/Http/routes.phpfile
  3. Database config file is in config/database.phpfile
  1. User模型在app/User.php文件中
  2. 路线在app/Http/routes.php文件中
  3. 数据库配置文件在config/database.php文件中