feriatos / api-key-bundle
为使用ApiKey身份验证创建了一种途径,适用于Symfony2。需要FOSUserBundle。
3.0.0
2016-01-14 16:26 UTC
Requires
- php: >=5.3.0
- friendsofsymfony/user-bundle: ~2.0@dev
- symfony/symfony: >=2.3.0
README
为使用ApiKey身份验证创建了一种途径,适用于Symfony2。需要FOSUserBundle。
安装
需要composer,按照以下方式安装
composer require uecode/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提供了两种与用户模型交互的方式
- 使用此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