为什么Auth :: attempt总是在Laravel 5.3中返回false?

时间:2016-11-10 21:07:20

标签: php authentication laravel-5.3

我是Laravel的新人。我尝试在Laravel 5.3中使用Multiple Auth,我的auth.php文件是:

<?php

return [

    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],

        'courier' => [
            'driver' => 'session',
            'provider' => 'couriers',
        ],

        'client' => [
            'driver' => 'session',
            'provider' => 'clients',
        ]
    ],

    'providers' => [
        'couriers' => [
            'driver' => 'eloquent',
            'model' => App\Courier::class,
        ],

        'clients' => [
            'driver' => 'eloquent',
            'model' => App\Client::class,
        ],

        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ]
    ],

    'passwords' => [
        'couriers' => [
            'provider' => 'couriers',
            'table' => 'password_resets',
            'expire' => 60,
        ],

        'clients' => [
            'provider' => 'clients',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

然后,当我在数据库中存储客户端或Couriers时,我使用bcrypt作为密码(也可以使用函数Hash::make()作为密码)。例如,我的模型Courier是:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Courier extends Authenticatable
{
  [..]

  public function setPasswordAttribute($pass){
        $this->attributes['password'] = bcrypt($pass);
    }

  [..]
}

当更新快递员时,在我的控制器中我有:

public function update(Request $request, $id) {

        $fieldsCourier = $request->all();
        $courier = Courier::find($id);

        if( isset($fieldsCourier['password']) )
            $fieldsCourier['password'] = bcrypt($fieldsCourier['password']);

        if( $courier->update($fieldsCourier) )
            $courier = Courier::find($id);

    }

我有一个名为authenticate的方法,但方法尝试总是返回false(invalid_credentials)。即便这样发送有效的凭证..这是我的代码:

public function authenticate(Request $request) {
        $credentials = $request->only('email', 'password');

        try {
            if ( auth()->guard('courier')->attempt($credentials) ){
                $user = Auth::guard('courier')->user();
            } else {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        return response()->json(compact('user'));
    }

我不知道我做错了什么。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您已在模型和控制器上加密密码两次。

只需删除其中一个

例如:不要在控制器上使用bcrypt,因为您已在模型上使用bcrypt