我正在使用Laravel构建API。为了进行身份验证和安全性,我使用的是Passport:https://laravel.com/docs/5.7/passport
我遵循了文档中的所有步骤。我正在使用通过身份验证的多个配置文件,但遇到一个问题,中间件使用的令牌可以应用于其他中间件。
在我的config / auth.php文件中,它看起来像这样:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'user' => [
'driver' => 'passport',
'provider' => 'users',
],
'producer' => [
'driver' => 'passport',
'provider' => 'producers',
],
'coordinator' => [
'driver' => 'passport',
'provider' => 'coordinators',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'producers' => [
'driver' => 'eloquent',
'model' => App\Producer::class,
],
'coordinators' => [
'driver' => 'eloquent',
'model' => App\Coordinator::class,
],
],
协调器模型如下:
class Coordinator extends Authenticatable{
use HasApiTokens, Notifiable;
protected $table = 'coordinators';
protected $guard = 'coordinator';
protected $fillable = [
'coordinator_name', 'email', 'password', 'cpf_cnpj', 'phone'
];
protected $hidden = [
'password',
];
public function events(){
return $this->belongsToMany('App\Event')->using('App\EventCoordinator');
}}
模型生产者如下所示:
class Producer extends Authenticatable{
use HasApiTokens, Notifiable;
protected $guard = 'producer';
protected $fillable = [
'name', 'email', 'password', 'cpf_cnpj', 'phone', 'street', 'neighborhood', 'city', 'state', 'number', 'zipcode', 'complement'
];
protected $table = 'producers';
protected $hidden = [
'password',
];
public function events(){
return $this->hasMany('App\Event');
}}
在使用我在auth.php中设置的中间件的路线上
Route::middleware('auth:producer')->group(function() {
Route::get('events', 'ProducerController@events');
});
Route::middleware('auth:coordinator')->group(function() {
Route::get('events', 'CoordinatorController@events');
});
最后,CoordinatorController中的events方法看起来像这样:
public function events(){
try{
if(Auth::guard('coordinator')->check()){
$events = Auth::user()->events;
return response()->json(['events' => $events], 200);
}else{
return response()->json(['error' => ['message' => 'Usuário não autenticado.']], 421);
}
}catch(\Exception $err){
return response()->json(['error' => ['code' => $err->getCode(), 'message' => $err->getMessage()]], 400);
}
}
以及在ProducerController中:
public function events(){
try{
try{
if(Auth::guard('producer')->check()){
$events = Auth::user()->events;
return response()->json(['events' => $events], 200);
}else{
return response()->json(['error' => ['message' => 'Usuário não autenticado.']], 421);
}
}catch(\Exception $err){
return response()->json(['error' => ['code' => $err->getCode(), 'message' => $err->getMessage()]], 400);
}
}
我正在使用Postman进行测试,当我使用Producer令牌访问Coordinator方法时,即使在路由中使用了不同的中间件,它也可以正常工作。有人可以帮忙吗?缺少什么了吗?