我对laravel范围部分感到有点困惑。
我有一个用户模型和表格。
如何为用户分配用户,客户和/或管理员的角色。
我有一个带有vue和laravel api后端的SPA。我使用https://laravel.com/docs/5.3/passport#consuming-your-api-with-javascript
Passport::tokensCan([
'user' => 'User',
'customer' => 'Customer',
'admin' => 'Admin',
]);
如何指定哪个用户模型具有哪个范围?
或者范围与角色不同?
你会如何实现这个?
提前致谢!
答案 0 :(得分:52)
或者范围与角色不同?
两者之间最大的区别在于它们适用的背景。基于角色的访问控制(RBAC)在使用Web应用程序直接时管理用户的访问控制,而Oauth-2范围控制对 {{3}的API资源的访问代表用户。
如何指定哪个用户模型具有哪个范围?
在一般的Oauth流程中,要求用户(作为资源所有者)授权客户代表他/她可以做什么和不能做什么,这些就是你所谓的范围。在成功授权后,客户请求的范围将 external client ,而不是用户本身。
根据您选择的Oauth授权流程,客户端应在其请求中包含范围。在授权代码授予流程中,当将用户重定向到授权页面时,范围应包含在HTTP GET查询参数中,而在密码授予流程中,范围必须包含在HTTP POST正文参数中以请求令牌。
你会如何实现这个?
这是密码授权流程的示例,假设您事先已完成 assigned to the generated token 设置
定义管理员和用户角色的范围。尽可能具体,例如:admin可以管理订单,用户只能读取它。
// in AuthServiceProvider boot
Passport::tokensCan([
'manage-order' => 'Manage order scope'
'read-only-order' => 'Read only order scope'
]);
准备REST控制器
// in controller
namespace App\Http\Controllers;
class OrderController extends Controller
{
public function index(Request $request)
{
// allow listing all order only for token with manage order scope
}
public function store(Request $request)
{
// allow storing a newly created order in storage for token with manage order scope
}
public function show($id)
{
// allow displaying the order for token with both manage and read only scope
}
}
使用api guard和范围分配路由
// in api.php
Route::get('/api/orders', 'OrderController@index')
->middleware(['auth:api', 'scopes:manage-order']);
Route::post('/api/orders', 'OrderController@store')
->middleware(['auth:api', 'scopes:manage-order']);
Route::get('/api/orders/{id}', 'OrderController@show')
->middleware(['auth:api', 'scopes:manage-order, read-only-order']);
发布令牌时,首先检查用户角色,然后根据该角色授予范围。为此,我们需要一个额外的控制器,它使用AuthenticatesUsers特性来提供登录端点。
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
class ApiLoginController extends Controller
{
use AuthenticatesUsers;
protected function authenticated(Request $request, $user)
{
// implement your user role retrieval logic, for example retrieve from `roles` database table
$role = $user->checkRole();
// grant scopes based on the role that we get previously
if ($role == 'admin') {
$request->request->add([
'scope' => 'manage-order' // grant manage order scope for user with admin role
]);
} else {
$request->request->add([
'scope' => 'read-only-order' // read-only order scope for other user role
]);
}
// forward the request to the oauth token request endpoint
$tokenRequest = Request::create(
'/oauth/token',
'post'
);
return Route::dispatch($tokenRequest);
}
}
为api登录端点添加路由
//in api.php
Route::group('namespace' => 'Auth', function () {
Route::post('login', 'ApiLoginController@login');
});
而不是POST到/ oauth / token路由,而是POST到我们之前提供的api登录端点
// from client application
$http = new GuzzleHttp\Client;
$response = $http->post('http://your-app.com/api/login', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => 'user@email.com',
'password' => 'my-password',
],
]);
return json_decode((string) $response->getBody(), true);
成功授权后,将为客户端应用程序发出基于我们之前定义的范围的access_token和refresh_token。保留该位置,并在向API发出请求时将令牌包含在HTTP标头中。
// from client application
$response = $client->request('GET', '/api/my/index', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
],
]);
API现在应该返回
{"error":"unauthenticated"}
每当使用具有under privilege的令牌消耗受限制的端点时。
答案 1 :(得分:4)
实施Raymond Lagonda响应并且效果非常好,只需要注意以下事项。 您需要覆盖ApiLoginController中的AuthenticatesUsers特性的一些方法:
/**
* Send the response after the user was authenticated.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
// $request->session()->regenerate(); // coment this becose api routes with passport failed here.
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
?: response()->json(["status"=>"error", "message"=>"Some error for failes authenticated method"]);
}
/**
* Get the failed login response instance.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
return response()->json([
"status"=>"error",
"message"=>"Autentication Error",
"data"=>[
"errors"=>[
$this->username() => Lang::get('auth.failed'),
]
]
]);
}
如果您将login:username字段更改为自定义用户名字段,例如:e_mail。您必须像在LoginController中一样优化用户名方法。 此外,您还必须重新定义和编辑方法:validateLogin,attemptLogin,凭证,因为一旦验证登录,请求将转发到护照,并且必须称为用户名。
答案 2 :(得分:2)
我已经设法使用@RaymondLagonda解决方案,使用 Sentinel Laravel 5.5 ,但它应该也可以,没有Sentinel。
解决方案需要一些类方法覆盖(所以请记住,以备将来更新),并为api路由添加一些保护(例如,不暴露client_secret)。
第一步,修改你的ApiLoginController
以添加构造函数:
public function __construct(Request $request){
$oauth_client_id = env('PASSPORT_CLIENT_ID');
$oauth_client = OauthClients::findOrFail($oauth_client_id);
$request->request->add([
'email' => $request->username,
'client_id' => $oauth_client_id,
'client_secret' => $oauth_client->secret]);
}
在此示例中,您需要在.env中定义var('PASSPORT_CLIENT_ID')并创建OauthClients模型,但您可以通过在此处输入正确的测试值来安全地跳过此步骤。
需要注意的一点是,我们将$request->email
值设置为用户名,只是为了坚持Oauth2惯例。
第二步是覆盖导致sendLoginResponse
等错误的Session storage not set
方法,我们这里不需要会话,因为它是api。
protected function sendLoginResponse(Request $request)
{
// $request->session()->regenerate();
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
第三步是修改@RaymondLagonda建议的经过验证的方法。您需要在此处编写自己的逻辑,尤其是配置范围。
最后一步(如果您使用的是Sentinel)是修改AuthServiceProvider
。添加
$this->app->rebinding('request', function ($app, $request) {
$request->setUserResolver(function () use ($app) {
return \Auth::user();
// return $app['sentinel']->getUser();
});
});
在引导方法中$this->registerPolicies();
之后。
完成这些步骤之后,您应该能够通过提供用户名('这将始终是电子邮件,在此实施中'),密码和grant_type ='密码'
来使您的api工作此时,您可以添加到中间件范围scopes:...
或scope:...
以保护您的路线。
我希望,这真的会有所帮助...
答案 3 :(得分:1)
我知道这有点晚了,但是如果您使用网络中间件中的CreateFreshApiToken
在SPA中使用后端API,那么您只需添加“管理员”即可。中间件到你的应用程序:
php artisan make:middleware Admin
然后在\App\Http\Middleware\Admin
中执行以下操作:
public function handle($request, Closure $next)
{
if (Auth::user()->role() !== 'admin') {
return response(json_encode(['error' => 'Unauthorised']), 401)
->header('Content-Type', 'text/json');
}
return $next($request);
}
确保您已将role
方法添加到\App\User
以检索用户角色。
现在您需要做的就是在app\Http\Kernel.php
$routeMiddleware
中注册您的中间件,如下所示:
protected $routeMiddleware = [
// Other Middleware
'admin' => \App\Http\Middleware\Admin::class,
];
并将其添加到routes/api.php
Route::middleware(['auth:api','admin'])->get('/customers','Api\CustomersController@index');
现在,如果您在未经许可的情况下尝试访问api,您将收到" 401 Unauthorized"错误,您可以在应用中检查和处理。
答案 4 :(得分:1)
使用@RaymondLagonda解决方案。如果您收到类范围未找到错误,请将以下中间件添加到$routeMiddleware
文件的app/Http/Kernel.php
属性中:
'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,`
此外,如果您收到错误Type error: Too few arguments to function
,您应该可以从请求中获取$user
,如下所示。
(我正在使用laratrust来管理角色)
public function login(Request $request)
{
$email = $request->input('username');
$user = User::where('email','=',$email)->first();
if($user && $user->hasRole('admin')){
$request->request->add([
'scope' => 'manage-everything'
]);
}else{
return response()->json(['message' => 'Unauthorized'],403);
}
$tokenRequest = Request::create(
'/oauth/token',
'post'
);
return Route::dispatch($tokenRequest);
}
答案 5 :(得分:-1)
感谢您,这个问题让我有些困惑!我采用了雷蒙德·拉贡达(Raymond Lagonda)的解决方案,使用内置速率限制,使用单个thirdparty
客户端(或根据需要进行更多定制),针对Laravel 5.6对其进行了一些自定义,同时仍为每个用户提供了权限列表(范围)。
password
授予并遵循Oauth流程routes / api.php
Route::group(['namespace' => 'ThirdParty', 'prefix' => 'thirdparty'], function () {
Route::post('login', 'ApiLoginController@login');
});
ThirdParty / ApiLoginController.php
<?php
namespace App\Http\Controllers\ThirdParty;
use Hash;
use App\User;
use App\ThirdParty;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class ApiLoginController extends Controller
{
use AuthenticatesUsers;
/**
* Thirdparty login method to handle different
* clients logging in for different reasons,
* we assign each third party user scopes
* to assign to their token, so they
* can perform different API tasks
* with the same token.
*
* @param Request $request
* @return Illuminate\Http\Response
*/
protected function login(Request $request)
{
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$user = $this->validateUserLogin($request);
$client = ThirdParty::where(['id' => config('thirdparties.client_id')])->first();
$request->request->add([
'scope' => $user->scopes,
'grant_type' => 'password',
'client_id' => $client->id,
'client_secret' => $client->secret
]);
return Route::dispatch(
Request::create('/oauth/token', 'post')
);
}
/**
* Validate the users login, checking
* their username/password
*
* @param Request $request
* @return User
*/
public function validateUserLogin($request)
{
$this->incrementLoginAttempts($request);
$username = $request->username;
$password = $request->password;
$user = User::where(['email' => $username])->first();
abort_unless($user, 401, 'Incorrect email/password.');
$user->setVisible(['password']);
abort_unless(Hash::check($password, $user->password), 401, 'Incorrect email/password.');
return $user;
}
}
config / thirdparties.php
<?php
return [
'client_id' => env('THIRDPARTY_CLIENT_ID', null),
];
ThirdParty.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ThirdParty extends Model
{
protected $table = 'oauth_clients';
}
.env
## THIRDPARTIES
THIRDPARTY_CLIENT_ID=3
php artisan make:migration add_scope_to_users_table --table = users
// up
Schema::table('users', function (Blueprint $table) {
$table->text('scopes')->nullable()->after('api_access');
});
// down
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('scopes');
});
(注意:api_access
是一个标志,它决定用户是否可以登录到应用程序的网站/前端部分,查看仪表板/记录等),
routes / api.php
Route::group(['middleware' => ['auth.client:YOUR_SCOPE_HERE', 'throttle:60,1']], function () {
...routes...
});
MySQL-用户范围
INSERT INTO `users` (`id`, `created_at`, `updated_at`, `name`, `email`, `password`, `remember_token`, `api_access`, `scopes`)
VALUES
(5, '2019-03-19 19:27:08', '2019-03-19 19:27:08', '', 'hello@email.tld', 'YOUR_HASHED_PASSWORD', NULL, 1, 'YOUR_SCOPE_HERE ANOTHER_SCOPE_HERE');
MySQL-
ThirdParty
Oauth客户端
INSERT INTO `oauth_clients` (`id`, `user_id`, `name`, `secret`, `redirect`, `personal_access_client`, `password_client`, `revoked`, `created_at`, `updated_at`)
VALUES
(3, NULL, 'Thirdparty Password Grant Client', 'YOUR_SECRET', 'http://localhost', 0, 1, 0, '2019-03-19 19:12:37', '2019-03-19 19:12:37');
cURL-登录/请求令牌
curl -X POST \
http://site.localhost/api/v1/thirdparty/login \
-H 'Accept: application/json' \
-H 'Accept-Charset: application/json' \
-F username=hello@email.tld \
-F password=YOUR_UNHASHED_PASSWORD
{
"token_type": "Bearer",
"expires_in": 604800,
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciO...",
"refresh_token": "def502008a75cd2cdd0dad086..."
}
正常使用长寿命的access_token / refresh_token!
访问禁止范围
{
"data": {
"errors": "Invalid scope(s) provided."
},
"meta": {
"code": 403,
"status": "FORBIDDEN"
}
}