[英]Laravel 4 Auth::attempt() always returns false
我正在嘗試Laravel的Auth類,但每當我嘗試登錄用戶時,該方法返回false。 這是我的代碼:
routes.php文件
Route::get('new-user', function() {
return View::make('register');
});
Route::post('new-user', function() {
$name = Input::get('name');
$email = Input::get('email');
$password = Hash::make(Input::get('password'));
$user = new User;
$user->name = $name;
$user->email = $email;
$user->password = $password;
$user->save();
});
Route::get('login', function() {
return View::make('login');
});
Route::post('login', function() {
$user = array(
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password'))
);
if (Auth::attempt($user)) {
//return Redirect::intended('dashboard');
return "ok.";
} else {
return "Wrong.";
}
});
意見/ login.blade.php
{{ Form::open(array('url' => 'login', 'method' => 'post')) }}
<h1>Login:</h1>
<p>
{{ Form::label('email', 'Email: ') }}
{{ Form::text('email') }}<br />
{{ Form::label('password', 'Password: ') }}
{{ Form::password('password') }}<br />
</p>
<p>
{{ Form::submit('Login') }}
</p>
{{ Form::close() }}
配置/ auth.php
return array(
'driver' => 'eloquent',
'model' => 'User',
'table' => 'users',
'reminder' => array(
'email' => 'emails.auth.reminder', 'table' => 'password_reminders',
),
);
數據庫具有電子郵件和密碼字段,密碼字段為varchar(60)。 每當我將登錄信息發送到/ login時,它都會返回“Wrong”。 我真的看不出這里有什么不對嗎?
您的代碼是錯誤的,因為您將錯誤的變量傳遞給Auth::attempt()
。 該方法需要一個包含密鑰用戶名,密碼的數組,並可選擇記住。 鑒於此,您的上述代碼應為:
Route::post('login', function()
{
$credentials = [
'username' => Input::get('email'),
'password' => Input::get('password')
];
dd(Auth::attempt($credentials));
});
希望有所幫助。
此外,我將為您提供額外代碼的片段,以改善您的工作流程。 存儲新用戶的路線:
Route::post('register', function()
{
$input = Input::only(['username', 'email', 'password']);
// validate data
Eloquent::unguard();
$user = User::create($input);
Auth::loginUsingId($user->id);
return Redirect::to('dashboard');
});
然后在您的用戶模型中添加方法
public function setPasswordAttribute()
{
$this->password = Hash::make($this->password);
}
這樣,密碼將在每次設置時自動散列
在嘗試之前不要哈希密碼:
$user = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($user)) {
//return Redirect::intended('dashboard');
return "ok.";
} else {
return "Wrong.";
}
這不起作用,因為auth :: attempt使用bcrypt將密碼轉換為hash,並在users表中查找匹配的hash。
簡而言之,密碼應該是存儲在數據庫表中的哈希值,用於auth ::嘗試工作。
這就是你的if()條件失敗的原因。
您可以使用bcrypt(密碼)將密碼存儲為數據庫中的哈希值,然后使用auth :: attempt
以下是來自laravel docs
https://laravel.com/docs/5.2/authentication#authenticating-users
attempt方法接受一個鍵/值對數組作為其第一個參數。 數組中的值將用於查找數據庫表中的用戶。 因此,在上面的示例中,將通過電子郵件列的值檢索用戶。 如果找到用戶,則將存儲在數據庫中的散列密碼與通過陣列傳遞給方法的散列密碼值進行比較。 如果兩個散列密碼匹配,則將為用戶啟動經過身份驗證的會話。
如果身份驗證成功,則嘗試方法將返回true。 否則,將返回false。
您應該在模型類中實現laravel提供的UserInterface
類:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface
{
請記住,它有2個抽象方法,您應該在模型中聲明。 您可以遵循原始的User.php
模型
檢查密碼長度。 數據庫中必須為60或更高。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.