Symfony 使用自定义身份验证登录

Symfony 使用自定义身份验证登录,symfony,Symfony,我想要一个带有自定义字段的登录,以验证平台中的用户。 关键是要检查字段“pw\u expires\u at”到\DateTime('now'),以记录用户 以下是我到目前为止所做的: 在控制器中: $user->setPassword( $passwordEncoder->encodePassword( $user, $mdp) ); $user->setPwExpiresAt(new \DateTime("now + 1 minute"));

我想要一个带有自定义字段的登录,以验证平台中的用户。 关键是要检查字段“pw\u expires\u at”到
\DateTime('now')
,以记录用户

以下是我到目前为止所做的:

在控制器中:

$user->setPassword(
    $passwordEncoder->encodePassword(
    $user,    
    $mdp)
);

$user->setPwExpiresAt(new \DateTime("now + 1 minute"));

$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
在验证器中:

public function checkCredentials($credentials, UserInterface $user)
{
    $valid = false;
    $validDate = $this->checkDate($credentials, $user);
    $validPassword = $this->passwordEncoder->isPasswordValid($user, $credentials['password']);

    if($validDate && $validPassword) {
        $valid = true;
    }

    return $valid;

}

/**
 * @return bool
 */
public function checkDate($credentials, UserInterface $user){

    $now = new \DateTime('now');
    $pwdate = new \DateTime();

    $pwdate = $this->entityManager->getRepository(Users::class)->findOneBy([
        'email' => $credentials['email']
    ]);

    if ($pwdate > $now) {
        return false;
    }
    else {
        return true;
    }
}
我还在AuthenticatorInterface.php中添加了新函数
checkDate()

问题是:我可以随时登录。

您正在比较(
)用户对象
存储库->findBy(…)
,它返回一个
Users::class
和一个
DateTime
对象
$now=new\DateTime()

另外,
$user
对象entityManager响应很可能是您的
getUsername
函数返回的同一个对象(您在该函数中作为参数传递的对象),因此可以跳过吗?如果DTO不包含此过期值,则将其重新添加。
此外,您不再使用任何凭据,因此也将其删除

我会将其更改为:

public function checkDate(UserInterface $user) {
    $now = new \DateTime();

    $pwdate = $user->getPwExpiresAt();

    // we dont need the if/else as this ($pwdate > $now)
    // is an expression and will already return true/false;
    return $pwdate > $now; 
}
还有一些建议:

  • 您可能需要重新考虑将函数重命名为更具表现力的函数,如
    $this->hasAuthenticationExpired($user)
    这应该清楚地指示函数正在执行的操作,而不是“检查日期(为了什么?!)”而不必通读函数

  • 可以将此函数移动到用户对象,如
    public function haseexpired(){return$this->getpweexpiresat()&&new\DateTime()>$this->getpweexpiresat();}
    只要调用
    if(!$user->haseexpired()){
    ,这实际上是许多人的首选方式,因为无论何时何地处理用户对象,都可以轻松重用和访问它


您的行
$pwdate=$this->entityManager…
没有任何意义。结果对象是用户,而不是日期时间。显然,将用户与日期时间进行比较总是错误的(无论这意味着什么),因此您的checkdate总是返回true。我猜您缺少了
->getPwExpiresAt()
call或其他什么。另外,您的逻辑是错误的,checkdate应该是false,当$now>$pwdate时。非常感谢。事实上,逻辑是错误的。我还有很多东西要学……还感谢您给我一些提示,让我有一个更清晰的代码!:)