semitono / api-key-bundle
为使用 ApiKey 认证提供 Symfony2 的途径。需要 FOSUserBundle。
3.0.1
2022-07-11 21:03 UTC
Requires
- php: ^5.3|^7.0
- friendsofsymfony/user-bundle: ^1|~2.0@dev
- symfony/symfony: ^2.3|^3.0
Replaces
- uecode/api-key-bundle: 3.0.0
README
为使用 ApiKey 认证提供 Symfony2 的途径。需要 FOSUserBundle。是 uecode/api-key-bundle
包的新替代品
安装
需要 composer,按照以下步骤进行安装
composer require semitono/api-key-bundle
启用 Bundle
在您的 AppKernel.php
中放置以下代码以启用该 Bundle
<?php // app/AppKernel.php public function registerBundles() { $bundles = array( // ... new Uecode\Bundle\ApiKeyBundle\UecodeApiKeyBundle(), ); }
配置
您可以根据需要更改 API 密钥的传递方式和传递参数的名称。默认情况下,此 Bundle 在查询字符串中查找 api_key
。
uecode_api_key: delivery: query #or header parameter_name: some_value # defaults to `api_key`
更新用户提供者
此 Bundle 提供两种与用户模型协同工作的方式
- 使用此 Bundle 提供的模型和用户提供者
- 使用自定义用户提供者
使用此 Bundle 提供的模型
实体
假设您已经有一个扩展 FOSUserBundle 基础用户模型的 User
类,更改扩展,使其扩展 Uecode\Bundle\ApiKeyBundle\Model\ApiKeyUser
然后更新您的模式。
更改使用的用户提供者
在您的安全配置中,将提供者更改为服务 uecode.api_key.provider.user_provider
security: providers: db: id: uecode.api_key.provider.user_provider # Or providers: chain_provider: chain: providers: [db, memory] memory: # ..... db: id: uecode.api_key.provider.user_provider
使用自定义用户提供者
为了与该 Bundle 协同工作,您的用户提供者应实现 ApiKeyUserProviderInterface
。它包含一个用于通过 apiKey 加载用户的方法。您应为此接口实现用于在您的 api 防火墙中使用的用户提供者。
use Uecode\Bundle\ApiKeyBundle\Security\Authentication\Provider\ApiKeyUserProviderInterface; class MyCustomUserProvider implements ApiKeyUserProviderInterface { // ... public function loadUserByApiKey($apiKey) { return $this->userManager->findUserBy(array('apiKey' => $apiKey)); } }
更改安全设置
您现在可以添加 api_key: true
和 stateless: true
到任何防火墙中。
例如
security: firewalls: auth: pattern: ^/api/* api_key: true stateless: true provider: db # Required if you have multiple providers and firewalls