dozxos6346 2016-10-26 17:21
浏览 37

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

I am trying to make Auth for an API Rest manually, but the response for Auth::attempt is always false.

Route

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

Controller

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);
    }
}

I have userd Hash::make to encrypt the password on the user creation.

My model is:

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');
    }
}

What am I doing wrong?

EDIT

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

Thats my user creation. If this helps I didn't launch `php artisan make:auth', may this order be necessary?

  • 写回答

1条回答 默认 最新

  • douxi8759 2016-10-27 07:21
    关注

    of course it always false because you did not use correct way to get the json in your request using laravel
    the correct way is

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

    not

    $input = $request->all();
    

    so your controller would be like this

    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);
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥30 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题