我正在尝试手动为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',这个命令可能是必要的吗?
答案 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);
}
}