我有一个loginAction
,我试图从数据库获取用户并登录她。
似乎使用的是"主要"防火墙规则,而不是secure_area
规则。 因为我得到:
No Authentication Provider found for token of class "Symfony'Component'Security'Core'Authentication'Token'UsernamePasswordToken"
如果我添加
guard:
authenticators:
- token_authenticator
到"主要"防火墙规则,然后错误消失,但token_authenticator
接管,我在所有路由上都Authentication Required
如果我在登录后转储$token
或session
,我可以看到我的用户在那里。
知道我做错了什么吗?
public function loginAction(Request $request)
{
if ($request->isMethod('POST')) {
$userManager = $this->container->get('entity.user');
$hasEmail = $this->getDoctrine()->getRepository('AppBundle:User')->findOneBy([
'email' => $request->request->get('email'),
'password' => $request->request->get('password'),
]);
// if credentials found
if ($hasEmail) {
// login the user
$token = new UsernamePasswordToken($hasEmail, $hasEmail->getPassword(), "secure_area", $hasEmail->getRoles());
$this->get("security.token_storage")->setToken($token);
$this->get('session')->set('_security_secure_area', serialize($token));
//$event = new InteractiveLoginEvent($request, $token);
//$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
} else {
$error = 'invalid credentials';
}
}
return [];
}
以下是我的防火墙规则:
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
provider: db_provider
main:
anonymous: ~
secure_area:
pattern: ^/
anonymous: ~
logout:
path: /logout
target: /
guard:
authenticators:
- token_authenticator
>Firewalls
通过pattern
集(路由参数的前缀(进行区分。因此,在您的情况下,随着main
防火墙接管,将永远达到secure_area
。
当您使用具有类似模式的路由时,您可以使用任何唯一模式(如 /secured
或 /api
(来访问防火墙。
此外,除非需要,否则不应显式处理用户登录。相反,您应该使用 $authenticationUtils
.请遵循此文档(适用于 2.8(。
在security.yml
中设置providers
和firewalls
取决于可以登录到应用程序的用户的来源。一旦你提到这些,这一点就会很清楚。
希望这有帮助!