我使用Laravel-Passport进行我的api端点的Laravel 5.8身份验证
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use Validator;
public function login(Request $request)
{
$validator = Validator::make($request->all('email', 'password'), [
'email' => 'required|string|email|max:255',
'password' => 'required|string|min:6'
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
};
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
return response()->json(['success' => $success], 200);
}
else{
return response()->json(['error'=>'Can not log in with the data provide.'], 401);
}
}
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
当我在POSTMAN上测试端点时,出现此错误:
错误原因是什么,如何解决?
BadMethodCallException 方法Illuminate \ Auth \ RequestGuard :: attempt不存在。
答案 0 :(得分:2)
我在测试最近添加的路由时遇到了同样的问题。清除缓存的路由为我解决了这个问题:
php artisan route:clear
答案 1 :(得分:0)
要使用用户名和密码登录用户,您需要使用web
身份验证保护,如下所示:
if(Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::guard('web')->user();