stalwart
stalwart

Reputation: 78

ZF2 + Apigility + Oauth2 Unit testing

I am trying to make some unit tests to my rest API done with apigility and secured with OAuth2 (zfcampus/zf-oauth2). Authentication and receiving access token works perfect

$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);

But however I try to send access token and access restricred resources I get "Access Denied". What is the proper way to send "access token"

Upvotes: 1

Views: 1788

Answers (1)

jel
jel

Reputation: 1172

You need to set your access token in your test directly using:

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

The zf-mvc-auth module uses bshaffer/oauth2-server-php/src/OAuth2/Request.php to build its bearer token request which grabs all of the parameters directly from the environment. Therefore, if you only set your token through Zend's Http\Header it won't work. For example:

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

Upvotes: 1

Related Questions