Laravel 5 RESTful API - 了解资源概念
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');
}
基本上我在控制器构造函数中注入请求,然后设置一个名为角色的操作。
然后我调用中间件 auth.basic 来设置用户。
最后调用中间件角色,根据请求中的角色数组检查用户角色,如果它有角色或者他是 root,则结果为真,否则我 return 错误:
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."}}
那是因为用户模型 return 不是角色。看我的 class:
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
创建它,然后将您的逻辑放入文件中已创建。在这种情况下,逻辑将检查用户(已登录)是否具有管理员权限。
编辑:
正如您在回复中指出的那样:
I dont user Route::post, I use Route::resource for handling RESTful API requests
因此您可以使用群组,请参阅:
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 指导我,你给了我基本的想法。我post 把它放在这里给所有需要的人。如何使用 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');
}
我正在用 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');
}
基本上我在控制器构造函数中注入请求,然后设置一个名为角色的操作。 然后我调用中间件 auth.basic 来设置用户。 最后调用中间件角色,根据请求中的角色数组检查用户角色,如果它有角色或者他是 root,则结果为真,否则我 return 错误:
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."}}
那是因为用户模型 return 不是角色。看我的 class:
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
创建它,然后将您的逻辑放入文件中已创建。在这种情况下,逻辑将检查用户(已登录)是否具有管理员权限。
编辑:
正如您在回复中指出的那样:
I dont user Route::post, I use Route::resource for handling RESTful API requests
因此您可以使用群组,请参阅:
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 指导我,你给了我基本的想法。我post 把它放在这里给所有需要的人。如何使用 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');
}