Laravel 手动身份验证:Auth::attempt 始终为 false

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

Laravel manual authentication: Auth::attempt always false

phplaravellaravel-5

提问by micky

i am using laravel manual authentication system.Submitting the form redirects to this route shown below.And in the authenticate () function the name and password never matches to which i stored earlier. i.e. Auth::attemptis always false.

我正在使用 laravel 手动身份验证系统。提交表单重定向到下面显示的这条路线。在 authentication() 函数中,名称和密码永远不会与我之前存储的匹配。即Auth::attempt总是假的。

 Route::post('/logintest', 'mycontroller@authenticate');
    Route::get('/home', ['middleware' => 'auth', function() {
  echo "home page";});
}]);

authenticate function:

验证功能:

public function authenticate(Request $request)
         {
            $input=$request->all();
            $password=$input['password'];
            $name=$input['name'];

            if (Auth::attempt(['Name' => $name, 'Password' => $password]) ){
            return redirect()->intended('/home');
        }   else 
          {
                return redirect('/login')->with('message','Error logging in!');
            }
        }

I've registered the user this way. the password is hashed using bcrypt(). function. but in authenticate() function i am comparing with plain password. i somewhere read Authautomatically handles it. OR Is there something should i change in config/auth.php because i've used name to authenticate instead of username?

我已经通过这种方式注册了用户。密码是使用 bcrypt() 散列的。功能。但是在 authentication() 函数中,我正在与普通密码进行比较。我在某处阅读Auth自动处理它。或者我是否应该在 config/auth.php 中更改某些内容,因为我使用名称而不是用户名进行身份验证?

public function register(Request $request)
{
    $input=$request->all();
    $password=bcrypt($input['password']);
    $name=$input['name'];
    $insert= User::insert(['Name'=>$name,'Password'=>$password]);
    return redirect('/login')
            ->with('message','successfully Registered.');
}

回答by lagbox

There is a problem with the names. Auth@attempttakes all those credentials, except password(case sensitive), that you pass in that array and runs a where query (This is how you can add extra constraints to the attempt, as they are just where conditions). If it finds a model it then will do a hash check on the passwordcredential (case sensitive) you passed and the model's hashed password which it gets from $model->getAuthPassword().

名字有问题。Auth@attempt获取所有这些凭据,除了password(区分大小写),您传入该数组并运行 where 查询(这是您可以向尝试添加额外约束的方式,因为它们只是 where 条件)。如果它找到一个模型,它将password对您传递的凭证(区分大小写)和它从$model->getAuthPassword().

This field in the credentials is a special one as it is what Auth needs so it knows what field in the credentials is meant to be the password. It does not correlate directly to the field you have used on your userstable, and must be named passwordin the credentials array. The other fields in the credentials you pass, besides 'password', do correlate directly to the fields on the users table as they are conditions for a database query on that table.

凭证中的这个字段是一个特殊的字段,因为它是 Auth 所需要的,因此它知道凭证中的哪个字段是密码。它与您在users表中使用的字段没有直接关系,必须password在凭据数组中命名。除了“密码”之外,您传递的凭据中的其他字段与用户表上的字段直接相关,因为它们是对该表进行数据库查询的条件。

You have to declare in your User model if you are using a field other than 'password' on the table as the password. In your case you are using 'Password'. (this is all case sensitive)

如果您使用表上的“密码”以外的字段作为密码,则必须在用户模型中声明。在您的情况下,您使用的是“密码”。(这都是区分大小写的)

class User ....
{
    ...
    public function getAuthPassword()
    {
        return $this->Password; // case sensitive
    }
    ...
}

When passing the credentials you pass the plain text password as there will be a hash_checkhappening, not a direct comparison.

传递凭据时,您将传递纯文本密码,因为这将hash_check发生,而不是直接比较。

You can name the fields what ever you want on your actual table, you just have to make Eloquent aware of this.

你可以在你的实际表上命名你想要的字段,你只需要让 Eloquent 意识到这一点。

回答by Javid Aliyev

Check the code below

检查下面的代码

public function authenticate(Request $request)
{
     $password = $request->input('password');
     $name = $request->input('name');

     if (Auth::attempt(['name' => $name, 'password' => $password]) )
     {
          return redirect()->intended('/home');
     }   
     else 
     {
          return view('login')->withErrors('Error logging in!');
     }
 }

回答by Ravi Hirani

You should write Password's p character in small letter.

你应该用小写字母写密码的 p 字符。

Replace,

代替,

Auth::attempt(['Name' => $name, 'Password' => $password])

to

Auth::attempt(['Name' => $name, 'password' => $password]) // 'p' is in small letter here.

check this linkalso.

也检查这个链接

回答by Chay22

As you're using name instead of email (default) as username to authenticate with. You should add $usernameproperty inside your AuthController.

当您使用名称而不是电子邮件(默认)作为用户名进行身份验证时。你应该$username在你的AuthController.

....

class AuthController extends Controller
{


use AuthenticatesAndRegistersUsers, ThrottlesLogins;

/**
 * Override the input name 'email'
 * Change it as the name on blade
 *
 * @var string $username
 */
protected $username = 'Name';

....
}

Alternatively, you can override loginUsername()method from Illuminate\Foundation\Auth\AuthenticatesUserstrait.

或者,您可以loginUsername()Illuminate\Foundation\Auth\AuthenticatesUserstrait覆盖方法。

....

class AuthController extends Controller
{


use AuthenticatesAndRegistersUsers, ThrottlesLogins;

/**
 * Get the login username to be used by the controller.
 *
 * @return string
 */
public function loginUsername()
{
    return 'Name';
}

....
}

Like others said, case matters. You then need to override getAuthPassword()method from Illuminate\Auth\Authenticatabletrait on your Usermodel

就像其他人说的,案例很重要。然后,您需要getAuthPassword()从模型Illuminate\Auth\Authenticatable上的 trait覆盖方法User

....

class User extends Authenticatable
{

....

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->Password;
    }
}

回答by CarlosCarucce

Try to switching to lowercase indexes in this line:

尝试在此行中切换到小写索引:

//...
if (Auth::attempt(['Name' => $name, 'Password' => $password]) ) {
//...

To

//...
if (Auth::attempt(['name' => $name, 'password' => $password]) ) {
//...

回答by Parvez Rahaman

If you want to use Nameas unique username and password fiendname as Password

如果您想使用Name唯一的用户名和密码 fiendname 作为Password

You can do this way..

你可以这样做..

In your AuthController add this method

在你的 AuthController 添加这个方法

public function loginUsername()
{
    return 'Name';
}

And in your User model add this method

并在您的 User 模型中添加此方法

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

Hope this will work.

希望这会奏效。

回答by Mohamed Elbiheiry

Why don't you use the command php artisan make:auth? It will make everything you need.

你为什么不使用命令php artisan make:auth?它会制作你需要的一切。

回答by VipindasKS

Route::group(['middleware' => ['web']], function () {
    Route::post('/logintest', 'mycontroller@authenticate'); 
});
  1. please check with the above change in your Routes.php, provided you are using version 5 or 5.2

  2. Make sure your users table field names are "Name" and "Password" else update it.

  3. Check the field length of your Passwordfield (in your database, userstable). It should hold a lengthy, hashed password something like this $2y$10$eM.kmjTwEIykhNUqMsNzMud0E6eO6RUYAzTqirrbozY1zdhVwQmsCatleast, (varchar(60))

  1. 如果您使用的是 5 或 5.2 版,请检查 Routes.php 中的上述更改

  2. 确保您的用户表字段名称是“名称”和“密码”,否则对其进行更新。

  3. 检查字段的字段长度Password(在您的数据库、users表中)。它应该$2y$10$eM.kmjTwEIykhNUqMsNzMud0E6eO6RUYAzTqirrbozY1zdhVwQmsC至少包含一个冗长的散列密码,(varchar(60))

It would be better if you could show us the users table schema

如果您能向我们展示 users 表架构会更好

  1. Finally, make sure you are entering the correct password (as I can't see much mistakes in your code)
  1. 最后,确保您输入了正确的密码(因为我看不到您的代码中有太多错误)

回答by linuxartisan

Everything appears to be correct.

一切似乎都是正确的。

What are the column names in the users table?

用户表中的列名是什么?

Names are case-sensitive. So make sure that they are indeed Nameand Passwordand not nameand password.

名称区分大小写。所以请确保它们确实是NameandPassword而不是nameand password