功能性测试 JWT 保护的 API
配置
例如,生成一些测试专用密钥
1 2
$ openssl genrsa -out config/jwt/private-test.pem -aes256 4096
$ openssl rsa -pubout -in config/jwt/private-test.pem -out config/jwt/public-test.pem
在您的 config_test.yml
中覆盖 bundle 配置
1 2 3 4
# config/test/lexik_jwt_authentication.yaml
lexik_jwt_authentication:
secret_key: '%kernel.project_dir%/config/jwt/private-test.pem'
public_key: '%kernel.project_dir%/config/jwt/public-test.pem'
提示: 如果您打算在 CI 服务器上运行测试,您可能需要提交这些密钥。
用法
创建一个已认证的客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/**
* Create a client with a default Authorization header.
*
* @param string $username
* @param string $password
*
* @return \Symfony\Bundle\FrameworkBundle\Client
*/
protected function createAuthenticatedClient($username = 'user', $password = 'password')
{
$client = static::createClient();
$client->jsonRequest(
'POST',
'/api/login_check',
[
'username' => $username,
'password' => $password,
]
);
$data = json_decode($client->getResponse()->getContent(), true);
$client->setServerParameter('HTTP_Authorization', sprintf('Bearer %s', $data['token']));
return $client;
}
/**
* test getPagesAction
*/
public function testGetPages()
{
$client = $this->createAuthenticatedClient();
$client->jsonRequest('GET', '/api/pages');
// ...
}
或者手动生成 JWT 令牌用于端到端测试
1 2 3 4 5 6 7 8 9 10 11
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
protected static function createAuthenticatedClient(array $claims)
{
$client = self::createClient();
$encoder = $client->getContainer()->get(JWTEncoderInterface::class);
$client->setServerParameter('HTTP_Authorization', sprintf('Bearer %s', $encoder->encode($claims)));
return $client;
}
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。