Symfony2機能テストで認証されたユーザーを使用する方法の回答で説明されているように? を使った簡単な解決策がありSymfony\Component\Security\Core\User\User
ます。
しかし、私は別の User クラス (いくつかの必要な追加フィールド) を持っており、それでユーザーを認証したいと考えています。
プロバイダーを設定するにはどうすればよいですか?
これはここで議論されているトリッキーな問題です: https://github.com/symfony/symfony/issues/5228 2.1 ですが、2.2 を使用している私にはまだ起こります。
テスト認証を行う方法は次のとおりです。
// Create a new client to browse the application
$client = static::createClient();
$client->getCookieJar()->set(new Cookie(session_name(), true));
// dummy call to bypass the hasPreviousSession check
$crawler = $client->request('GET', '/');
$em = $client->getContainer()->get('doctrine')->getEntityManager();
$user = $em->getRepository('MyOwnBundle:User')->findOneByUsername('username');
$token = new UsernamePasswordToken($user, $user->getPassword(), 'main_firewall', $user->getRoles());
self::$kernel->getContainer()->get('security.context')->setToken($token);
$session = $client->getContainer()->get('session');
$session->set('_security_' . 'main_firewall', serialize($token));
$session->save();
$crawler = $client->request('GET', '/login/required/page/');
$this->assertTrue(200 === $client->getResponse()->getStatusCode());
// perform tests in the /login/required/page here..
ああ、そして use ステートメント:
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\BrowserKit\Cookie;
フォームログインを使用していますか? またはhttpセキュリティ?
フォームログインを使用する場合、テストで行うことは、ログインフォームを介してログインしているユーザーをシミュレートすることです...
/**
* test of superuser ingelogd geraakt
*/
public function testSuperAdminLogin()
{
$crawler = $this->client->request('GET', '/login');
$form = $crawler->selectButton('Sign In')->form();
$user = $this->em->getRepository('NonoAcademyBundle:User')
->findOneByUsername('superadmin');
$crawler = $this->client
->submit($form,
array('_username' => $user->getUsername(),
'_password' => $user->getPassword()));
$this->assertTrue($this->client->getResponse()->isSuccessful());
$this
->assertRegExp('/\/admin\/notifications/',
$this->client->getResponse()->getContent());
}
次に、ログインしたユーザーとして機能するため、そのクライアントとクローラーを使用します。これがお役に立てば幸いです
特にフォームログインを使用している場合は、これらが役立つ場合もあります
private function doLogin()
{
$this->client = static::createClient();
$username = 'your-username';
$password = 'your-password';
$crawler = $this->client->request('GET', '/login');
$form = $crawler->filter('your-submit-button-classname')->form();
$crawler = $this->client
->submit($form,
array(
'_username' => $username,
'_password' => $password,
)
);
}
解決策を見つけました。
まず、ここでFakeUserProvider
説明されているように、新しいユーザー プロバイダーを作成する必要があります。
実装する必要があります。UserProviderInterface
必要loadUserByUsername
なユーザー オブジェクトを作成する必要があります。