前几天我有类似的问题。就像你说我无法找到合适的“预认证”,在这一点上我甚至可以在尝试认证之前执行我的支票。 (AuthenticationSuccess和AuthenticationFailure处理程序在我的情况下不是一种选择,因为我想在尝试之前阻止尝试)
但最终我发现了一种方法,在我的情况下确实有效(尽管可能存在更好的但我找不到它)。
如果您的应用程序正在使用默认的用户名/密码认证,你可以这样做:
延长UsernamePasswordFormAuthenticationListener
class UsernamePasswordFormAuthenticationListener extends \Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener
{
/** @var EntityManagerInterface */
protected $entityManager;
/**
* setter is called through DI container
*
* @param EntityManagerInterface $entityManager
*/
public function setEntityManager(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
/**
*
* @param Request $request
*
* @return null|RedirectResponse|\Symfony\Component\HttpFoundation\Response|\Symfony\Component\Security\Core\Authentication\Token\TokenInterface
*/
protected function attemptAuthentication(Request $request)
{
//do your logic and whatnot here
// i.E. return a redirect repsonse if the token is needed but missing
return parent::attemptAuthentication($request);
}
}
覆盖在你的services.yml原来的服务
security.authentication.listener.form:
class: AppBundle\Listener\UsernamePasswordFormAuthenticationListener
parent: security.authentication.listener.abstract
abstract: true
calls: [ [setEntityManager, ["@doctrine.orm.entity_manager"]] ]
(这里使用setter注入,因为构造函数需要像一吨的参数)
也许这种方式可能适合您的需求,没有人有一个更好的主意
来源
2017-05-05 07:55:17
Joe
这是完美的!因为我可以返回一个响应并将我的服务注入到监听器中,所以它非常完美。谢谢 ! ;) –