信息
您可以轻松更改数据库中的所有其他字段并将其用于身份验证。唯一的问题是
password领域。
实际上,
password字段在Laravel中以某种方式进行了硬编码(但不是很多人的想法),因此您不能随便在问题中传递数组。
默认情况下,如果您通过以下方式将数组传递给
attempt(以及可能的其他Auth函数,例如
validate或
once),则:
Auth::attempt(array( 'user_name' => 'admin', 'password' => 'hardpass',));
默认的Eloquent驱动程序将运行以下查询:
select * from `users` where `user_name` = 'admin' limit 1;
从数据库中获取此数据后,它将比较您提供的密码和创建的User对象的password属性。
但是,如果您仅使用:
Auth::attempt(array( 'user_name' => 'admin', 'passwd' => 'hardpass',));
将运行以下查询:
select * from `users` where `user_name` = 'admin' and `passwd` = 'hardpass' limit 1;
并且不会在数据库中找到任何用户(在
passwd您存储哈希密码的位置)。这是因为Eloquent从查询中删除,
password但使用任何其他数据来运行查询。另外,如果您尝试在这里使用,
'passwd'=> Hash:make($data['password'])尽管会找到用户,则比较密码将无法进行。
解
解决方案很容易。您需要这样运行
Auth::attempt:
Auth::attempt(array( 'user_name' => 'admin', 'password' => 'hardpass',));
如您所见,您仍然将
password键作为键传递(尽管该列不会在
users表中退出),因为只有这样,雄辩的驱动程序才不会将其用于构建查询。
现在,在
User模型(
app/models/User.php)文件中,您需要添加以下功能:
public function getAuthPassword() { return $this->passwd;}如您所见,您在此处使用数据库中真正存在的列:
passwd。
以这种方式使用它,您可以在列中输入任何您想要的密码,并且仍然可以使用默认的Eloquent驱动程序。
样本数据进行测试
我为此创建了一个非常简单的测试。
您只需要用
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";});- 创建空数据库并在其中设置连接数据
app/config/database.php
- 现在,您可以运行
/db
url例如http://localhost/yourprojectname/db
仅创建users表。 - 现在您可以运行
/
url-例如http://localhost/yourprojectname/
,您看到用户已登录,即使users
在数据库的表中您没有任何password
列(用于身份验证的数据已经以字符串形式传递,没有任何形式,但是在实际应用程序中,您将添加它们) )。您可以再次运行此网址-如您所见,用户仍处于登录状态,因此可以正常工作。 - 如果单击
Log out
链接,您将被注销
Laravel 5以上的更改
此解决方案已在Larave 4.2.9(如上所有内容)中以及在Laravel
5中进行了测试。在Laravel5中,所有工作原理都相同,但是您当然需要在不同路径下编辑文件:
User
模型已app/User.php
归档- 路线已
app/Http/routes.php
归档 - 数据库配置文件在
config/database.php
文件中



