使用基本http身份验证的REST单元测试始终为401 Unauthorized

时间:2017-05-04 15:52:25

标签: symfony security phpunit fosrestbundle

我正在使用基本的http身份验证制作REST api。

验证在浏览器和Postman中按预期工作,状态200 Ok,如果输入正确的凭据,控制器表现正常,否则401未经授权。

问题在于我正在努力使phpunit测试成功进行身份验证,它总是返回401 Unauthorized代码,我无法理解。

security.yml:

security:
providers:
    in_memory:
        memory:
            users:
                test:
                    password: testpass
                    roles: 'ROLE_TEST'

encoders:
    Symfony\Component\Security\Core\User\User: plaintext

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    default:
        anonymous: ~
        http_basic: ~

access_control:
    - { path: ^/api/test, roles: ROLE_TEST }

ApiControllerTest.php     

namespace ApiBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Response;

class ApiControllerTest extends WebTestCase
{
    public function testIndex()
    {

        $client = static::createClient();

        $crawler = $client->request(
            'GET',
            '/api/test/hello/unittestname',
            array(),
            array(),
            array(),
            array('PHP_AUTH_USER' => 'test', 'PHP_AUTH_PW' => 'testpass'));

        $this->assertSame(Response::HTTP_OK, $client->getResponse()->getStatusCode());

    }
}

启动测试:

1) ApiBundle\Tests\Controller\ApiControllerTest::testIndex
Failed asserting that 401 is identical to 200.

1 个答案:

答案 0 :(得分:2)

取决于documentation基本身份验证凭据应在$_SERVER中传递。 Symfony documentation“有关request()方法”部分的更多信息)中提到了同样的观点。

将凭据放入第五个参数 - server参数。

$crawler = $client->request(
    'GET',
    '/api/test/hello/unittestname',
    [],
    [],
    ['PHP_AUTH_USER' => 'test', 'PHP_AUTH_PW' => 'testpass']
);