使用 oauth2 保护路由

Protect routes with oauth2

我想通过使用 oauth2 身份验证来保护我的 REST API。我将 bshaffer/oauth2-server-php 与 zend 3 结合使用。
我有以下配置:

// autoload/oauth2.global.php
return [
  'zf-oauth2' => [
    'db' => [
      'dsn' => sprintf(
        'mysql:dbname=%s;host=%s',
        false !== getenv('DB_NAME') ? getenv('DB_NAME') : '',
        false !== getenv('DB_HOST') ? getenv('DB_HOST') : ''
      ),
      'username' => false !== getenv('DB_USER') ? getenv('DB_USER') : '',
      'password' => false !== getenv('DB_PASS') ? getenv('DB_PASS') : '',
    ],
    'storage' => MyApp\OAuth2Module\Adapter\PdoAdapter::class,
    'enforce_state' => true,
    'allow_implicit' => true,
    'access_lifetime' => 3600,
    'api_problem_error_response' => false,
    'options' => [
      'use_jwt_access_tokens' => false,
      'store_encrypted_token_string' => true,
      'use_openid_connect' => false,
      'id_lifetime' => 3600,
      'www_realm' => 'Service',
      'token_param_name' => 'access_token',
      'token_bearer_header_name' => 'Bearer',
      'require_exact_redirect_uri' => true,
      'allow_public_clients' => true,
      'allow_credentials_in_request_body' => true,
      'always_issue_new_refresh_token' => false,
      'refresh_token_lifetime' => 1209600,
    ],
  ],
];

我的授权路线是这样的:

// autoload/router.global.php
return [
  'router' => [
    'routes' => [
      'api' => [
        'type' => Literal::class,
        'options' => [
          'route' => '/api',
        ],
        'may_terminate' => false,
        'child_routes' => [
          'rest' => [
            'type' => Literal::class,
            'options' => [
              'route' => '/rest',
            ],
            'may_terminate' => false,
            'child_routes' => [
              'oauth' => [
                'type' => Literal::class,
                'options' => [
                  'route' => '/oauth',
                  'defaults' => [
                    'controller' => 'ZF\OAuth2\Controller\Auth',
                    'action' => 'token',
                  ],
                ],
              ],
            ],
          ],
        ],
      ],
    ],
  ],
];

到目前为止一切正常。我可以 post 我的客户端凭据到 oauth 端点并获得访问令牌。
但是我怎样才能保护其他端点呢? F.e。我向 /api/rest/myapp/GetList 发出 GET 请求。仅当用户还随请求发送授权持有人时,才应检索我的实体列表,但我找不到解决方案。是否可以在路由配置中设置参数(如 "require_token")以 "activate" 这种行为?或者保护我的 REST 的正确方法是什么 API?

没有内置系统可以做到这一点。您将创建一个侦听器 MvcEvent::Event_ROUTE 并将其放置在路由器之后,然后检查是否存在路由匹配。如果有,请检查它是否是受保护的路线。如果是应用认证逻辑。