tmsolution / api-key-bundle
为Symfony2创建了一个使用ApiKey认证的途径。需要FOSUserBundle。
v2.1.1
2015-11-06 08:45 UTC
Requires
- php: >=5.3.0
- friendsofsymfony/user-bundle: ~2.0@dev
- symfony/symfony: >=2.3.0
README
为Symfony2创建了一个使用ApiKey认证的途径。需要FOSUserBundle。
安装
需要composer,按照以下方式安装
composer require tmsolution/api-key-bundle dev-master
启用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提供两种与User模型交互的方式
- 使用此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