使用 OAuth2 和 ZF3-MVC 保护 REST API

Using OAuth2 and ZF3-MVC to protect REST API

我正在尝试让 https://github.com/zfcampus/zf-oauth2 使用我的 ZF3-MVC 应用程序(好的,一种解决方案可能是等待 Apigility 更新)。

我已经成功实现了 oauth2-server-php (https://github.com/bshaffer/oauth2-server-php),它的 zf- oauth2 模块支持 (https://github.com/zfcampus/zf-oauth2) 和适用于 ZF3 的 zf-oauth2 客户端 (https://github.com/API-Skeletons/zf-oauth2-client).

但是,我现在完全无法按照 zf-oauth2 模块的建议保护我的 API y:

You can protect your API using the following code (for instance, at the top of a controller):

if (!$this->server->verifyResourceRequest(OAuth2Request::createFromGlobals()))
{
    // Not authorized return 401 error
    $this->getResponse()->setStatusCode(401);
    return;
}

where $this->server is an instance of OAuth2\Server (see the AuthController.php).

我读过这个 post (Using ZF2 Oauth2) 但它不符合 ZF3。我想有一种比 copying/pasting zf-oauth2 模块的控制器和工厂从头开始实例化服务器更有效的方法。

有人知道如何在我的 API 控制器中实现 OAuth2\Server 的实例吗?

我终于自己搞定了。因为我在这上面花了很多时间,看到其他人也在寻找解决方案,所以我是这样做的。

首先,如果您不熟悉依赖注入和工厂(这是我的情况),我建议您阅读 https://docs.zendframework.com/tutorials/in-depth-guide/models-and-servicemanager/

module.config.php

// In module/YourModule/config/module.config.php:
namespace YourAppNamespace;

use Zend\ServiceManager\Factory\InvokableFactory;

return [
    'controllers' => [
        'factories' => [
            Controller\YourController::class => Factory\YourControllerFactory::class,
        ],
    ],
    'service_manager' => [ /** Your Service Manager Config **/ ]        
    'router' => [ /** Your Router Config */ ]
    'view_manager' => [ /** Your ViewManager Config */ ],
];

YourControllerFactory.php

// In module/YourModule/src/Controller/YourControllerFactory.php:
namespace YourAppNamespace\Factory;

use YourAppNamespace\Controller\YourController;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;

class YourControllerFactory implements FactoryInterface
{
    /**
     * @param ContainerInterface $container
     * @param string             $requestedName
     * @param null|array         $options
     *
     * @return YourController
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $controllerPluginManager = $container;
        $serviceManager          = $controllerPluginManager->get('ServiceManager');

        // Requires zf-campus/zf-oauth2
        $server   = $serviceManager->get('ZF\OAuth2\Service\OAuth2Server');
        $provider = $serviceManager->get('ZF\OAuth2\Provider\UserId');

        return new YourController($server, $provider);
    }
}

YourController.php

// In module/YourModule/src/Controller/YourController.php:
namespace YourAppNamespace\Controller;

use ZF\OAuth2\Controller\AuthController;
use OAuth2\Request as OAuth2Request;
use ZF\OAuth2\Provider\UserId\UserIdProviderInterface;

class YourController extends AuthController
{
    public function __construct($serverFactory, UserIdProviderInterface $userIdProvider)
    {
        parent::__construct($serverFactory, $userIdProvider);
    }

    public function indexAction()
    {
        $server = call_user_func($this->serverFactory, "oauth");

        if (!$server->verifyResourceRequest(OAuth2Request::createFromGlobals())) {
            // Failure
            $response = $server->getResponse();
            return $this->getApiProblemResponse($response);
        }

        // Success
        echo json_encode(array('success' => true, 'message' => 'It works!'));
    }
}

希望对您有所帮助!