Laravel 护照范围

2024-01-05

我对 laravel 范围部分有点困惑。

我有一个用户模型和表。

如何为用户分配用户、客户和/或管理员的角色。

我有一个带有 vue 和 laravel api 后端的 SPA。我用https://laravel.com/docs/5.3/passport#consuming-your-api-with-javascript https://laravel.com/docs/5.3/passport#consuming-your-api-with-javascript

    Passport::tokensCan([
        'user' => 'User',
        'customer' => 'Customer',
        'admin' => 'Admin',
    ]);

我如何分配哪个用户模型具有哪个范围?

或者范围与角色不一样?

你会如何实施这个?

提前致谢!


或者范围与角色不一样?

两者之间最大的区别在于它们适用的上下文。基于角色的访问控制 (RBAC) 管理用户在使用 Web 应用程序时的访问控制directly,而 Oauth-2 范围则控制对 API 资源的访问外部客户 https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2#oauth-roles代表用户。

我如何分配哪个用户模型具有哪个范围?

在一般的 Oauth 流程中,用户(作为资源所有者)被要求授权客户端代表他/她可以做和不能做的事情,这些就是您所说的scope. On 授权成功客户要求的范围是分配给生成的令牌 https://laravel.com/docs/5.3/passport#assigning-scopes-to-tokens不针对用户本身。

根据您选择的 Oauth 授权流程,客户端应在其请求中包含范围。在授权代码授权流程中,将用户重定向到授权页面时,范围应包含在 HTTP GET 查询参数中,而在密码授权流程中,范围必须包含在 HTTP POST 正文参数中才能请求令牌。

你会如何实施这个?

这是密码授予流程的示例,假设您已完成拉拉维尔/护照 https://laravel.com/docs/master/passport#installation预先设置

定义管理员和用户角色的范围。尽可能具体,例如:管理员可以管理订单,而用户只能读取它。

// 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 防护和范围分配路由

// 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' => '[email protected] /cdn-cgi/l/email-protection',
        '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"}

每当使用权限不足的令牌来消耗受限端点时。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 护照范围 的相关文章

随机推荐