用oauth2保护路线

时间:2018-02-06 16:11:13

标签: php rest oauth-2.0 zend-framework3

我想通过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',
                  ],
                ],
              ],
            ],
          ],
        ],
      ],
    ],
  ],
];

到目前为止一切正常。我可以将我的客户端凭据发布到oauth端点并获取访问令牌 但是我如何保护其他终端? F.E.我向/ api / rest / myapp / GetList发出GET请求。只有在用户也向请求发送授权承载但我无法找到解决方案时,才应检索我的实体列表。是否可以在路由配置中设置一个参数(例如" require_token")来激活"这个行为?或者保护我的REST API的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

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