我正在我的 symfony 应用程序中实现一个带有保护身份验证的登录系统。我已经开始实施该系统,但我一定做错了什么。
我将从展示我已经实现的内容开始,最后解释正在发生的事情......
安全.yml
security:
encoders:
UserBundle\Entity\User: bcrypt
providers:
custom_own_provider:
entity:
class: UserBundle:User
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
custom:
pattern: ^/ad/
anonymous: ~
provider: custom_own_provider
remember_me:
name: 'nothing'
secure: true
httponly: true
secret: '%secret%'
lifetime: 604800 # 1 week in seconds
path: /
domain: ~
guard:
authenticators:
- app.authenticator.form
服务.yml
services:
app.authenticator.form:
class: UserBundle\Security\LoginFormAuthenticator
autowire: true
arguments: ["@service_container"]
登录控制器
/**
* @Route("/login", name="login")
*/
public function loginAction(Request $request) {
$authenticationUtils = $this->get('security.authentication_utils');
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render(
'AppBundle:login:index.html.twig',
[
'error' => $error ? $error->getMessage() : NULL,
'last_username' => $lastUsername
]
);
}
带主页的公共控制器:登录成功后,用户被重定向到这里。碰巧在这里,当验证用户是否经过身份验证时,我不成功。安全令牌中的“getuser”返回“anon”。
/**
* @Route("/", name="homepage")
*/
public function publicHomepageAction (){
// DEBUG: This method gets a user from the Security Token Storage. The user here comes as 'anon'.
$user = $this->getUser();
// If user is already logged show internal homepage
$securityContext = $this->container->get('security.authorization_checker');
if($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')
|| $securityContext->isGranted('IS_AUTHENTICATED_FULLY')
){
// Code if user is authenticated
...
}
return $this->render('splash_page/homepage.html.twig');
}
最后,我的 FormAuthenticator:
class LoginFormAuthenticator extends AbstractGuardAuthenticator
{
private $container;
/**
* Default message for authentication failure.
*
* @var string
*/
private $failMessage = 'Invalid credentials';
/**
* Creates a new instance of FormAuthenticator
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* {@inheritdoc}
*/
public function getCredentials(Request $request)
{
if ($request->getPathInfo() != '/login' || !$request->isMethod('POST')) {
return;
}
return array(
'email' => $request->request->get('email'),
'password' => $request->request->get('password'),
);
}
/**
* {@inheritdoc}
*/
public function getUser($credentials, UserProviderInterface $userProvider)
{
$email = $credentials['email'];
return $userProvider->loadUserByUsername($email);
}
/**
* {@inheritdoc}
*/
public function checkCredentials($credentials, UserInterface $user)
{
$plainPassword = $credentials['password'];
$encoder = $this->container->get('security.password_encoder');
if (!$encoder->isPasswordValid($user, $plainPassword)) {
throw new CustomUserMessageAuthenticationException($this->failMessage);
}
return true;
}
/**
* {@inheritdoc}
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$url = $this->container->get('router')->generate('homepage');
return new RedirectResponse($url);
}
/**
* {@inheritdoc}
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
$url = $this->container->get('router')->generate('login');
return new RedirectResponse($url);
}
/**
* {@inheritdoc}
*/
public function start(Request $request, AuthenticationException $authException = null)
{
$url = $this->container->get('router')->generate('login');
return new RedirectResponse($url);
}
/**
* {@inheritdoc}
*/
public function supportsRememberMe()
{
return true;
}
/**
* Does the authenticator support the given Request?
*
* If this returns false, the authenticator will be skipped.
*
* @param Request $request
*
* @return bool
*/
public function supports (Request $request){
return $request->request->has('_username') && $request->request->has('_password');
}
}
我的用户实体实现了 UserInterface。
尽管在主页上它向我表明我已通过“匿名”身份验证,但如果我尝试再次登录,通过调试,我注意到它检测到我已通过身份验证并重定向到主页控制器,但在此控制器中它说我喜欢匿名并返回重定向到启动页面。
它给人的感觉是在验证和重定向到控制器之间的某个地方丢失了令牌存储。
任何想法?