我正在用Laravel 5开发一个RESTful API,我的routes.php文件中有一些资源,一切都正常工作。
但是现在我已经添加了auth.basic中间件,我想介绍用户角色,我感到很困惑。
在我的Controller中,我有一个构造函数来调用2中间件、auth.basic和角色中间件,但由于缺乏知识,无法继续。
我需要什么?那么,我需要设置用户角色,谁可以访问每个控制器,但不能做到这一点。我是控制器,我想访问用户来检查他的角色,并将其与在Controller上建立的角色进行比较,但是我不知道如何访问用户,您能帮我吗?
编辑:
我把它放在Controller的构造函数中
public function __construct(Request $request)
{
$actions = $request->route()->setAction( ['roles' => ['admin', 'seller', 'buyer']]);
$this->middleware('auth.basic');
$this->middleware('roles');
}基本上,我将请求注入控制器构造函数中,然后设置一个称为角色的操作。然后我调用中间件auth.basic来设置用户。最后一次调用中间件角色,它根据请求中的角色数组检查用户角色,如果它具有该角色或如果他是根用户,则结果为true,否则我将返回错误:
return response([
'error' => [
'code' => 'INSUFFICIENT_ROLE',
'description' => 'You are not authorized to access this resource.'
]
], 401);现在我有了一个错误,这个错误总是会:
{"error":{"code":"INSUFFICIENT_ROLE","description":"You are not authorized to access this resource."}}那是因为用户模型不返回角色。看我的课:
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['username', 'email', 'password', 'role_id'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
//Comprobacion del rol del usuario
public function hasRole($roles)
{
$this->have_role = $this->getUserRole();
// Check if the user is a root account
if($this->have_role->name == 'root') {
return true;
}
if(is_array($roles)){
foreach($roles as $need_role){
if($this->checkIfUserHasRole($need_role)) {
return true;
}
}
} else{
return $this->checkIfUserHasRole($roles);
}
return false;
}
private function getUserRole()
{
return $this->role()->getResults();
}
private function checkIfUserHasRole($need_role)
{
return (strtolower($need_role)==strtolower($this->have_role->name)) ? true : false;
}
//User relation with role
public function role(){
return $this->belongsTo('App\Role');
}
}出什么事了?
发布于 2015-10-23 09:35:48
找到解决办法!谢谢Phorce的指导,你给了我一些基本的想法。我把它寄给了所有需要的人。如何使用Laravel 5获得RESTful API的角色身份验证。
解释一下。在我为中间件调用构造函数的路由控制器中,首先使用注入的$request对象添加属性角色(可以访问该路由的角色集)。然后我调用中间件auth.basic来请求用户,然后调用另一个中间件来检查角色。安藤,就这样!都在工作。
中间件:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckRole
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//return $next($request);
// Get the required roles from the route
$roles = $this->getRequiredRoleForRoute($request->route());
// Check if a role is required for the route, and
// if so, ensure that the user has that role.
//print "HasRole:".$request->user()->hasRole($roles).".";
if($request->user()->hasRole($roles) || !$roles)
{
return $next($request);
}
return response([
'error' => [
'code' => 'INSUFFICIENT_ROLE',
'description' => 'You are not authorized to access this resource.'
]
], 401);
}
private function getRequiredRoleForRoute($route)
{
$actions = $route->getAction();
//print "actinos:".print_r($actions);
return isset($actions['roles']) ? $actions['roles'] : null;
}
}用户模型
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['username', 'email', 'password', 'role_id'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
protected $have_role;
protected $profile;
//Comprobacion del rol del usuario
public function hasRole($roles)
{
$this->have_role = $this->getUserRole();
//$this->have_role = $this->role()->getResults();
// Check if the user is a root account
if($this->have_role->nombre == 'root') {
return true;
}
if(is_array($roles)){
foreach($roles as $need_role){
if($this->checkIfUserHasRole($need_role)) {
return true;
}
}
} else{
return $this->checkIfUserHasRole($roles);
}
return false;
}
private function getUserRole()
{
return $this->role()->getResults();
}
private function checkIfUserHasRole($need_role)
{
if($need_role === $this->have_role->nombre){
return true;
}else{
return false;
}
//return (strtolower($need_role)==strtolower($this->have_role->name)) ? true : false;
}
//Relaciones de user
public function role(){
return $this->belongsTo('App\Role');
}
}路线:
Route::resource('perfiles','PerfilesUsuariocontroller',[ 'only'=>['index','show'] ]);控制器构造法
public function __construct(Request $request)
{
$actions = $request->route()->setAction( ['roles' => ['root', 'admin', 'seller']]);
$this->middleware('auth.basic');
$this->middleware('roles');
}发布于 2015-10-23 07:39:15
从你的问题中,我得到了以下几点:
我怎么处理这个中间件..。
那么,让我们假设您有两个中间件auth.basic,auth.admin
然后你可以让你的路线像:
Route::post('/api/getResponse', ['middleware' => 'auth', function () {
$var = "you have access to this route";
return json_encode($var);
}]);在这里,您将设置是否访问此特定路由的权限,在本例中,只有具有管理权限的人员才能访问该路由。
例如,如果您没有用于"admin“的中间件,您可以通过运行php artisan make:middleware admin命令来创建它,然后将您的逻辑放在已经创建的文件中。在本例中,逻辑将检查用户(登录)是否具有管理权限。
编辑:
正如你在答复中指出的那样:
我不使用用户路由::post,我使用路由::资源来处理RESTful API请求
因此,您可以使用一个组,请参见:
Route::group(['middleware' => 'admin'], function () {
Route::resource('API_USER', 'API_USER_CONTROLLER');
});这将允许您使用您的管理组作为组,因此,您所有的路线,有访问权可以进入这里。过去,我只是为我的所有用户组创建了单独的组,即admin有自己的,user有自己的,moderator有自己的。但是,我相信你可以使用以下方法:
Route::group(['before' => 'auth|admin'], function()
{
} 这个组的内容是:should be open to auth users OR admin,但我还没有对其进行全面测试。
https://stackoverflow.com/questions/33296914
复制相似问题