Laravel手动验证 - 永远不会工作

时间:2016-10-26 17:21:23

标签: php laravel-5

我正在尝试手动为API Rest创建Auth,但Auth :: attempt的响应始终为false。

路线

Route::group(["prefix"=>"api"], function(){
    Route::post('/login', [
        'as'    =>  'checkLogin',
        'uses'  =>  'LoginCtrl@checkLogin'
    ]);
});

控制器

class LoginCtrl extends Controller
{
    public function checkLogin(Request $request){
        $input = $request->all();
        if(Auth::attempt(['username' => $input['user'], 'password' => $input['password']])){
            $data = ["response"=>true,"access_token"=>"test"];
        }else{
            $data = ["response"=>false,"access_token"=>"none"];
        }
        return response()->json($data);
    }
}

我有用户Hash::make来加密用户创建的密码。

我的模特是:

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $table = "usuarios";
    protected $username = 'username';

    protected $fillable = [
        'name', 'username', 'password'
    ];

    protected $hidden = [
        //'password', 'remember_token',
    ];

    public $timestamps = false;

    public function access_token(){
        return $this->hasOne('App\AccessToken');
    }
}

我做错了什么?

修改

$user = new User();
$user->username = "myFreshUsername";
$user->password = Hash::make('userPwd');
$user->save();

这就是我的用户创建。如果这有助于我没有启动`php artisan make:auth',这个命令可能是必要的吗?

1 个答案:

答案 0 :(得分:1)

当然它总是假的,因为你没有使用正确的方法来使用laravel来获取你的请求中的json 正确的方法是

$input  = $request->json()->all();

$input = $request->all();

所以你的控制器就像这样

class LoginCtrl extends Controller
{
    public function checkLogin(Request $request){
        $input  = $request->json()->all();
        if(Auth::attempt(['username' => $input['user'], 'password' => $input['password']])){
            $data = ["response"=>true,"access_token"=>"test"];
        }else{
            $data = ["response"=>false,"access_token"=>"none"];
        }
        return response()->json($data);
    }
}