我正在开发需要为多个用户生成访问令牌的 Laravel 应用程序。我使用 Laravel Passport 和密码授予来颁发令牌。我已遵循 Laravel 文档,但似乎我做错了什么,因为当我尝试使用 Postman 调用我的 API 端点(学生)时,我被重定向到登录路由。后来我发现重定向来自我创建的中间件,但我仍然不知道出了什么问题
验证文件
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
'api-student' => [
'driver' => 'passport',
'provider' => 'students',
'hash' => false,
]
];
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'students' => [
'driver' => 'eloquent',
'model' => App\Student::class,
],
],
api.php
Route::post('auth/getlogin', 'Api\StudentController@authenticate')->middleware('auth:api-student');
//Api\StudentController
public function authenticate(Request $request, Student $user)
{
$credentials = [
'username'=>$request->username,
'password'=>$request->password];
if(!Auth::guard('api-student')->attempt($credentials)) {
return response()->json([
'message'=>'Error'
], 401);
}
if(Auth::guard('api-student')->attempt($credentials)){
$user = Auth::guard('client');
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Username or password incorrect'], 401);
}
}
富国沪深