具有基本 http 身份验证的 REST 单元测试始终为 401 Unauthorized
Unit test on REST with basic http authentication is always 401 Unauthorized
我正在制作带有基本 http 身份验证的 REST api。
身份验证在浏览器和 Postman 中按预期工作,如果凭据输入正确,状态 200 Ok 和控制器表现良好,否则为 401 Unauthorized。
问题是我正在努力使 phpunit 测试成功通过身份验证,它总是 returns 401 未经授权的代码,我不明白为什么。
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.
取决于 documentation 应在 $_SERVER
中传递基本身份验证凭据。
Symfony documentation("More about the request() Method"节)
中提到了相同点
将凭据放入第五个参数 - server
个参数。
$crawler = $client->request(
'GET',
'/api/test/hello/unittestname',
[],
[],
['PHP_AUTH_USER' => 'test', 'PHP_AUTH_PW' => 'testpass']
);
我正在制作带有基本 http 身份验证的 REST api。
身份验证在浏览器和 Postman 中按预期工作,如果凭据输入正确,状态 200 Ok 和控制器表现良好,否则为 401 Unauthorized。
问题是我正在努力使 phpunit 测试成功通过身份验证,它总是 returns 401 未经授权的代码,我不明白为什么。
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.
取决于 documentation 应在 $_SERVER
中传递基本身份验证凭据。
Symfony documentation("More about the request() Method"节)
将凭据放入第五个参数 - server
个参数。
$crawler = $client->request(
'GET',
'/api/test/hello/unittestname',
[],
[],
['PHP_AUTH_USER' => 'test', 'PHP_AUTH_PW' => 'testpass']
);