【问题标题】:ZF2 + Apigility + Oauth2 Unit testingZF2 + Apigility + Oauth2 单元测试
【发布时间】:2014-06-22 15:42:34
【问题描述】:

我正在尝试使用 apigility 对我的其余 API 进行一些单元测试,并使用 OAuth2 进行保护 (zfcampus/zf-oauth2)。身份验证和接收访问令牌完美运行

$this->dispatch('/api/oauth', HttpRequest::METHOD_POST, array(
        'username' => 'username',
        'password' => 'password',
        'client_id' => 'web-app',
        'grant_type' => 'password'
    ), true);

    /** @var $response \Zend\Http\PhpEnvironment\Response */
    $response = $this->getResponse();
    $phpNative = \Zend\Json\Json::decode($response->getContent(), \Zend\Json\Json::TYPE_OBJECT);
    echo "\n".$phpNative->access_token."\n";
    $this->assertResponseStatusCode(200);

但是,我尝试发送访问令牌并访问受限资源,但我得到“拒绝访问”。发送“访问令牌”的正确方法是什么

【问题讨论】:

标签: php unit-testing rest zend-framework2 oauth-2.0


【解决方案1】:

您需要直接在测试中设置访问令牌:

$_SERVER['HTTP_AUTHORIZATION'] = 'Bearer asdfghjkl';

zf-mvc-auth 模块使用 bshaffer/oauth2-server-php/src/OAuth2/Request.php 构建其承载令牌请求,该请求直接从环境中获取所有参数。因此,如果你只通过 Zend 的 Http\Header 设置你的令牌,它是行不通的。例如:

$headers = new \Zend\Http\Headers;
$header = $headers->fromString("Authorization:Bearer asdfghjkl");
$this->getRequest()->setHeaders($header);

【讨论】:

    猜你喜欢
    • 2013-01-25
    • 2015-07-07
    • 1970-01-01
    • 2017-08-29
    • 2015-11-14
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多