控制器Symfony 2外部的条令查询



自从两天以来,我在使用控制器外部的UserRepository进行查询时遇到了一些问题。我正试图从数据库中获取一个名为ApiKeyAuthenticator的类的用户。我想像文档中那样在函数getUsernameForApiKey中执行查询。我想我应该使用donctline作为一种服务,但我不知道如何做到这一点。

感谢您的提前帮助!

<?php
// src/AppBundle/Security/ApiKeyUserProvider.php
namespace AppBundleSecurity;

use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityCoreUserUser;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityCoreExceptionUnsupportedUserException;
class ApiKeyUserProvider implements UserProviderInterface
{
public function getUsernameForApiKey($apiKey)
{
// Look up the username based on the token in the database, via
// an API call, or do something entirely different
$username = ...;
return $username;
}
public function loadUserByUsername($username)
{
return new User(
$username,
null,
// the roles for the user - you may choose to determine
// these dynamically somehow based on the user
array('ROLE_API')
);
}
public function refreshUser(UserInterface $user)
{
// this is used for storing authentication in the session
// but in this example, the token is sent in each request,
// so authentication can be stateless. Throwing this exception
// is proper to make things stateless
throw new UnsupportedUserException();
}
public function supportsClass($class)
{
return User::class === $class;
}
}

您必须将ApiKeyUserProvider作为服务,并将UserRepository作为依赖项注入。不确定存储库是否是2.8中的服务,所以可能需要注入EntityManager

class ApiKeyUserProvider implements UserProviderInterface
{
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}

public function loadUserByUsername($username)
{
$repository = $this->em->getRepository(User::class);
// ...

现在在services.yml文件中将您的类注册为服务

services:
app.api_key_user_provider:
class:     AppBundleSecurityApiKeyUserProvider
arguments: ['@doctrine.orm.entity_manager']

最新更新