phphd / api-testing
API 测试的 JWT 认证
Requires
- php: >=8.1
- lexik/jwt-authentication-bundle: ^2.0 || ^3.0
Requires (Dev)
- phphd/coding-standard: ~0.5.3
- phpstan/phpstan: ^1.10
- phpstan/phpstan-phpunit: ^1.3
- phpunit/phpunit: ^9.4
- psalm/plugin-phpunit: ^0.18.4
- symfony/var-dumper: ^6.0
- tomasvotruba/type-coverage: ^0.2.1
- vimeo/psalm: ^5.16
Conflicts
- symfony/config: <6.0 || >=8.0
- symfony/dependency-injection: <6.1 || >=8.0
- symfony/http-kernel: <6.0 || >=8.0
- symfony/security-core: <6.0 || >=8.0
This package is auto-updated.
Last update: 2024-09-16 11:25:15 UTC
README
🧰 为 Symfony 应用程序提供轻量级的 jwt 授权工具,用于 API 测试。本质上,此软件包将 Lexik JWT Authentication Bundle 集成到您的 API 测试用例中。
快速入门
安装 📥
-
使用 composer 安装
composer require --dev phphd/api-testing
-
在
bundles.php
中启用该包PhPhD\ApiTesting\Bundle\PhdApiTestingBundle::class => ['test' => true],
配置 ⚒️
在 config/packages/test
目录下创建 phd_api_testing.yaml
配置文件。在此处指定应用程序 用户提供者 的服务 ID。如果您只有一个认证用户实体(因此只有一个提供者),请使用当前默认配置。
phd_api_testing: jwt_authenticators: - name: default user_provider: security.user_providers
使用 🚀
在您的 API 测试类中使用 JwtLoginTrait
和 login
方法来处理认证
use PhPhD\ApiTesting\Jwt\JwtLoginTrait; final class ExampleProtectedApiTest extends ApiTestCase { use JwtLoginTrait; // ... public function testAccessFeatureWithoutPassword(): void { $token = $this->login('username'); $this->client->request('GET', '/api/protected-route', [ 'auth_bearer' => $token, ]); self::assertResponseStatusCodeSame(200); } }
在此示例中,使用 login
生成 username
用户的 jwt 令牌,以便以他的名义发送 API 请求。
高级配置 ⚙️
多个认证器
根据您的特定需求,可以使用多个认证器。例如,如果您在主认证应用程序旁边有管理面板,您可能想使用专用认证器。
本质上,如果您正在使用 security.user_providers
,通常不需要额外的配置,因为 security.user_providers
作为链式用户提供者,这意味着将使用从任何从属提供者找到的第一个用户。
尽管如此,在存在冲突的用户名或其他特定原因的情况下,您可以在同一配置文件中通过不同的名称注册额外的认证器
phd_api_testing: jwt_authenticators: - name: admin user_provider: security.user.provider.concrete.api_admin_user_provider
在此配置中,api_admin_user_provider
是 security.yaml
中用户提供者的名称,而 admin
- 只是我们测试中使用的别名。
注册认证器后,我们可以使用其别名作为 login
方法的第二个参数
public function testDedicatedAdminAuthenticator(): void { $token = $this->login('admin@test.com', authenticator: 'admin'); $this->client->request('GET', '/api/admin/protected-route', [ 'auth_bearer' => $token, ]); self::assertResponseStatusCodeSame(200); }