使用ZF2 Oauth2

时间:2014-06-02 13:53:50

标签: php zend-framework2 oauth-2.0 apigility

我试图让https://github.com/zfcampus/zf-oauth2使用我的应用程序(主要是因为我已经安装了apigility并且zf-oauth2附带了它)。

我正在阅读最后一节并说它要保护,我只是简单地使用以下代码(例如,在控制器的顶部):

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).

然而,必须以某种方式注入$ this->服务器。但是,我似乎无法找到注入方式和注意事项。通过单击链接查看AuthController.php,我找到了一个页面...

编辑: 感谢Tom和Ujjwal,我认为我更近了一步。

在我的控制器中,现在我有以下内容:

use ZF\OAuth2\Controller\AuthController;

class BaseController extends AuthController
{

}

在我的Module.php中,我尝试注入OAuth2Server:

public function getServiceConfig()
{
    return array(
       'factories' => array(
            '\Stand\Controller\BaseController' =>  function ($sm) {
                $cls = new BaseController($sm->get('ZF\OAuth2\Service\OAuth2Server'));
                return $cls;
            },
        )
    );
}

但是,当我尝试渲染页面时,它并没有捕获我的注入。我得到了

  

捕获致命错误:参数1传递给ZF \ OAuth2 \ Controller \ AuthController :: __ construct()必须是OAuth2 \ Server的实例

请指教!

由于

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式创建工厂:

module.config.php

<?php
return array(
    'controllers' => array(
        'factories' => array(
            'Test\Controller\Test' => function($sm) {
                $locator = $sm->getServiceLocator();
                $server = $locator->get('ZF\OAuth2\Service\OAuth2Server');
                $provider = $locator->get('ZF\OAuth2\Provider\UserId');
                return new Test\Controller\TestController($server, $provider);
            }
        )
    ),
...

然后你可以在你的控制器类中使用它:

<?php
namespace Test\Controller;

use ZF\OAuth2\Controller\AuthController;
use ZF\OAuth2\Provider\UserId\UserIdProviderInterface;
use Zend\View\Model\JsonModel

class TestController 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($this->getOAuth2Request())) {
            $response   = $server->getResponse();
            return $this->getApiProblemResponse($response);
        } 

        return new JsonModel(array("Hello" => "World!"));
    }    

}

参考:https://framework.zend.com/manual/2.1/en/modules/zend.service-manager.quick-start.html