【发布时间】:2018-02-06 16:11:13
【问题描述】:
我想通过使用 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 的正确方法是什么?
【问题讨论】:
标签: php rest oauth-2.0 zend-framework3