[英]Laravel 5 RESTful API - Understanding resource concepts
我正在开发与Laravel 5.我有我的一些资源一个RESTful API routes.php
文件,一切工作正常。
但现在我添加了auth.basic
中间件,我想介绍用户角色,我感到困惑。
在我的控制器中,我有一个构造函数来调用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');
}
基本上我在控制器构造函数中注入请求,然后我设置了一个名为roles的操作。 然后我调用中间件auth.basic来设置用户。 最后调用中间件角色,它根据请求中的角色数组检查用户角色,如果它有角色,或者如果他是root,则结果为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');
}
}
怎么了?
从你的问题,我得到以下内容:
我如何处理auth中间件......
好吧,我们假设您有两个中间件auth.basic
, auth.admin
然后你可以让你的路线像:
Route::post('/api/getResponse', ['middleware' => 'auth', function () {
$var = "you have access to this route";
return json_encode($var);
}]);
在这里,您设置是否以及谁有权访问此特定路由,在这种情况下,只有拥有管理员权限的人才能访问它。
例如,如果你没有“admin”的中间件,你可以通过运行artisan命令php artisan make:middleware admin
来创建它,然后将你的逻辑放在已经创建的文件中。 在这种情况下,逻辑将检查用户(已登录)是否具有管理员权限。
编辑:
正如你在答复中指出的那样:
我不使用Route :: post,我使用Route :: resource来处理RESTful API请求
因此,您可以使用组,请参阅:
Route::group(['middleware' => 'admin'], function () {
Route::resource('API_USER', 'API_USER_CONTROLLER');
});
这样您就可以将管理组用作GROUP,因此,所有可以访问的路由都可以在此处输入。 在过去,我刚刚为我的所有用户组创建了单独的组,即admin
拥有它自己的, user
将拥有自己的,而moderator
将拥有它自己的组。 但是,我相信你可以使用以下内容:
Route::group(['before' => 'auth|admin'], function()
{
}
该组内容如下: should be open to auth users OR admin
但我还没有对此进行全面测试。
找到解决方案!!!!! 感谢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'] ]);
Controller Constructor方法
public function __construct(Request $request)
{
$actions = $request->route()->setAction( ['roles' => ['root', 'admin', 'seller']]);
$this->middleware('auth.basic');
$this->middleware('roles');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.