See the Authentication chapter for a guide on how to configure an OAuth 2.0 provider.

Authentication - 认证 章节,了解怎么配置 OAuth 2.0 provider。

Defining Route Scopes 定义路由 scopes

By using scopes you’ll have more control over who can access your protected endpoints. Scopes can be set on a group or a route as either an array of pipe delimited string.

通过使用 scopes,你可以对你的受保护的 API 拥有更多的控制。scopes 可以被设置在一个分组或一个路由上,使用数组或者管道分隔的字符串。

Route Group Scopes 路由分组 scopes

  1. $api->version('v1', ['middleware' => 'api.auth', 'scopes' => ['read_user_data', 'write_user_data']], function ($api) {
  2. // Only access tokens with the "read_user_data" scope will be given access.
  3. });

Specific Route Scopes 特定路由 scopes

  1. $api->version('v1', ['middleware' => 'api.auth'], function ($api) {
  2. $api->get('user', ['scopes' => 'read_user_data', function () {
  3. // Only access tokens with the "read_user_data" scope will be given access.
  4. }]);
  5. });

Controller Scopes 控制器 Scopes

If your controllers use the Dingo\Api\Routing\Helpers trait you can use the scopes method.

如果你的控制器使用 Dingo\Api\Routing\Helpers trait,那么你可以使用 scopes 方法。

  1. use Dingo\Api\Routing\Helpers;
  2. class UserController extends Controller
  3. {
  4. use Helpers;
  5. public function __construct()
  6. {
  7. $this->scopes('read_user_data');
  8. }
  9. }

You can define the methods you want the scopes to apply to via the second parameter, either as a pipe separated string or as an array. If you do not supply the methods then the scopes will apply to all methods. You can also use the except and only array keys to apply the scopes to a subset of methods.

利用第二个参数,你可以定义 scopes 申请的地方,可以使用管道分隔的字符串或者一个数组。如果你没有提供方法,那么 scopes 将适用于所有方法。你也可以适用 exceptonly 数组键去适用于方法的子集。

  1. use Dingo\Api\Routing\Helpers;
  2. class UserController extends Controller
  3. {
  4. use Helpers;
  5. public function __construct()
  6. {
  7. // Only apply to the index method.
  8. $this->scopes('read_user_data', 'index');
  9. // Apply to every method except the store method.
  10. $this->scopes('read_user_data', ['except' => 'store']);
  11. // Apply only to the store method.
  12. $this->scopes('write_user_data', ['only' => ['store']]);
  13. }
  14. public function index()
  15. {
  16. //
  17. }
  18. public function store()
  19. {
  20. //
  21. }
  22. }

← Internal Requests | Making Requests To Your API →