Symfony 使用基本http身份验证对REST进行单元测试始终是未经授权的
我正在制作一个带有基本http身份验证的RESTAPI 验证在浏览器和邮递员中按预期工作,如果凭据输入正确,状态200 Ok,控制器表现正常,否则 问题是我正在努力使phpunit测试成功地进行身份验证,它总是返回401个未经授权的代码,我不知道为什么 security.yml:Symfony 使用基本http身份验证对REST进行单元测试始终是未经授权的,symfony,security,phpunit,fosrestbundle,Symfony,Security,Phpunit,Fosrestbundle,我正在制作一个带有基本http身份验证的RESTAPI 验证在浏览器和邮递员中按预期工作,如果凭据输入正确,状态200 Ok,控制器表现正常,否则 问题是我正在努力使phpunit测试成功地进行身份验证,它总是返回401个未经授权的代码,我不知道为什么 security.yml: security: providers: in_memory: memory: users: test:
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.
取决于应在$\u服务器中传递的基本身份验证凭据。
在(“关于request()方法的更多信息”部分)中也提到了同样的一点
将凭证放入第五个参数-服务器
参数
$crawler = $client->request(
'GET',
'/api/test/hello/unittestname',
[],
[],
['PHP_AUTH_USER' => 'test', 'PHP_AUTH_PW' => 'testpass']
);
您是否以该用户身份登录?首先尝试匿名,并使用以下-{path:^/api/test,role:IS\u AUTHENTICATED\u ANONYMOUSLY}
配置您的应用程序,顺便说一句,role不是roles@RodolVelasco,我在这个文档后面使用了“角色”:就是这样,我发现一些来源将凭证放在第6个参数中,我应该坚持使用sf2文档。谢谢