使用OAuth2和ZF3-MVC来保护REST API

时间:2016-07-23 10:23:34

标签: zend-framework oauth-2.0 zend-framework-mvc zend-framework3 zf3

我正在尝试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(https://github.com/API-Skeletons/zf-oauth2-client)的zf-oauth2客户端。

然而,在zf-oauth2模块的推荐之后,我现在总是试图保护我的API:

  

您可以使用以下代码保护您的API(例如,在控制器的顶部):

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

其中$ this->服务器是OAuth2 \ Server的一个实例(请参阅AuthController.php)。

我已阅读此帖(Using ZF2 Oauth2),但它不符合ZF3。我想有一种更有效的方法,而不是复制/粘贴zf-oauth2模块的控制器和工厂来从头开始实例化服务器。

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

1 个答案:

答案 0 :(得分:4)

我终于靠自己做了。由于我花了相当多的时间在这上面,并看到其他人也在寻找解决方案,这就是我如何做到的。

首先,如果您不熟悉依赖注入和工厂(我的情况就是这样),建议您阅读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!'));
    }
}

希望它有所帮助!