无法基于角色Laravel 8保护路由 [英] Can't protect Routes based on role Laravel 8
本文介绍了无法基于角色Laravel 8保护路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用中间件保护基于角色的路由。
我正在测试此路由,以便只允许administrador
角色能够进入它。
Route::get('/gestionarMedicos', [PersonaController::class,'mostrarMedicos'])->name('personaMostrarMedicos')->middleware('auth','firstLogin','role:administrador');
这是我的中间件代码(在路由中称为route)
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateHttpRequest;
class EnsureUserHasRole
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next, $role)
{
if (! $request->user()->hasRole($role)) {
// Redirect...
return back();
}
return $next($request);
}
}
这是用户模型的代码
<?php
namespace AppModels;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use IlluminateDatabaseEloquentModel;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'role',
'name',
'email',
'password',
'idPersona',
'estado'
];
public function Persona(){
return $this->belongsTo(Persona::class,'idPersona');
}
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'remember_token'
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function hasRole($role)
{
return User::where('role', $role)->get();
}
}
某些逻辑没有正确执行,因为即使没有该角色的用户也可以访问路由
中间件中的dd()是用来测试的,我用它得到了";adminadrador";。
我已尝试Patrick Obafemi解决方案,但仍然存在同样的问题。
为了测试,我对基于Patrcik回答结果的if做了dd,结果是假的。
我不确定逻辑问题在哪里。
如果有帮助,我还将发布我的数据库模型的图片。
推荐答案
下面的链接回答了该问题。
Middleware doesn't protect routes based on role
还介绍了在需要为多个角色保护路由的情况下如何保护路由。该条件是错误的,因为它提供了具有管理员角色的用户的集合。条件应如下所示,仅允许所需角色访问路由
if (!$request->user() || $request->user()->role != $role) {
// Redirect...
return back();
}
对于多个角色,您可以访问链接,其中的答案解释了如何允许多个所需角色访问路由。
可能Patrick的回答是正确的,但此处也回答了问题。
这篇关于无法基于角色Laravel 8保护路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文