【发布时间】:2017-07-05 08:54:09
【问题描述】:
很可能我遗漏了一些愚蠢的东西,但我花了很多时间在这上面,所以任何帮助都非常感谢。
身份验证基于this tutorial
我正在使用 bcrypt 对密码进行编码,并且似乎在用户注册时工作正常。
但是登录时会抛出下面的错误,即使输入的密码是正确的:
凭据无效。
我确认电子邮件和密码正确到达登录验证器(登录表单是通过 Ajax 提交的)。
getUser() 方法似乎也在完成从数据库中检索 $user 对象和相应密码的工作。
security.yml设置如下:
security:
encoders:
UsedBundle\Entity\User:
algorithm: bcrypt
这是注册控制器:
namespace UsedBundle\Controller;
use UsedBundle\Form\UserType;
use UsedBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use UsedBundle\Service\sendEmail;
class RegistrationController extends Controller
{
/**
* @Route("/inscription", name="inscription")
*/
public function registerAction(Request $request)
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
if ($request->isMethod('POST')) {
$form->submit($request->request->get($form->getName('user')));
if(!$form->isValid()){
// handle invalid form
}
if ($form->isSubmitted() && $form->isValid()) {
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$user->setUserKey( $user->getEmail() );
$user->setUserKeyTime();
$user->setDateReg();
$em = $this->getDoctrine()->getManager('used');
$em->persist($user);
$em->flush();
return new JsonResponse(array(
'status' => 'ok',
'message' => 'Success!')
);
}
}else{
return $this->render(
'common/register.html.twig',
array('form' => $form->createView())
);
}
}
}
登录表单验证器(设置为服务):
namespace UsedBundle\Security;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use UsedBundle\Entity\User;
use UsedBundle\Repository\UserRepository;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
class FormLoginAuthenticator extends AbstractFormLoginAuthenticator
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getCredentials(Request $request)
{
if ($request->getPathInfo() != '/login_check') {
return;
}
$username = $request->request->get('_email');
$request->getSession()->set(Security::LAST_USERNAME, $username);
$password = $request->request->get('_password');
return array(
'username' => $username,
'password' => $password
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$username = $credentials['username'];
$user = $this->container
->get('doctrine')
->getRepository('UsedBundle:User', 'used')
->findOneByemail( $username );
return $user;
}
public function checkCredentials($credentials, UserInterface $user)
{
$plainPassword = $credentials['password'];
$encoder = $this->container->get('security.password_encoder');
if (!$encoder->isPasswordValid($user, $plainPassword)){
throw new BadCredentialsException();
}else{
$this->pass_error = 'no error';
}
}
protected function getLoginUrl()
{
return $this->container->get('router')
->generate('homepage');
}
protected function getDefaultSuccessRedirectUrl()
{
return $this->container->get('router')
->generate('homepage');
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
// AJAX! Return some JSON
if ($request->isXmlHttpRequest()) {
return new JsonResponse(
array('userId' => $token->getUser()->getId(),
'statut' => 'ok'
)
);
}
// for non-AJAX requests, return the normal redirect
return parent::onAuthenticationSuccess($request, $token, $providerKey);
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
return new JsonResponse(
array('message' => $exception->getMessageKey(),
'statut' => 'error',
'passerror' => $this->pass_error )
);
}
按要求摘录 checkCredentials() 上的 var_dump($user)
object(UsedBundle\Entity\User)#329 (15) {
["id":"UsedBundle\Entity\User":private]=>
int(7)
["avatar":"UsedBundle\Entity\User":private]=>
string(11) "dsfdfafadfa"
["name":"UsedBundle\Entity\User":private]=>
string(9) "dfdffadfa"
["password":"UsedBundle\Entity\User":private]=>
string(64) "jjuewij/sc9Af17i+ZXAUcrdiZX83HHMLjTNVSnJ34qGCp6BAxisVtjiG3Nm+uH5"
["plainPassword":"UsedBundle\Entity\User":private]=>
NULL
["email":"UsedBundle\Entity\User":private]=>
string(22) "myemail@gmail.com"
["phone":"UsedBundle\Entity\User":private]=>
string(12) "445454545454"
["roles":"UsedBundle\Entity\User":private]=>
string(9) "ROLE_USER"
["isActive":"UsedBundle\Entity\User":private]=>
bool(true)
根据要求,onAuthenticationFailure() 上 var_dump($exception) 的摘录
object(Symfony\Component\Security\Core\Exception\BadCredentialsException)#322 (8) {
["token":"Symfony\Component\Security\Core\Exception\AuthenticationException":private]=>
object(Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken)#61 (6) {
["credentials":"Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken":private]=>
array(2) {
["username"]=>
string(22) "myemail@gmail.com"
["password"]=>
string(8) "senha444"
}
["guardProviderKey":"Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken":private]=>
string(6) "main_0"
["user":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
NULL
["roles":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
array(0) {
}
["authenticated":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
bool(false)
["attributes":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
array(0) {
}
}
["message":protected]=>
string(0) ""
["string":"Exception":private]=>
string(0) ""
["code":protected]=>
int(0)
["file":protected]=>
string(78) "/Users/BAMAC/Sites/Symfony1/src/UsedBundle/Security /FormLoginAuthenticator.php"
["line":protected]=>
int(58)
【问题讨论】:
-
$user是在checkCredentials中加载的吗?你能提供一个var_dump或一些确认吗? -
也许您可以仅出于调试目的执行以下操作:
$tempPass = $encoder->encodePassword($user, $plainPassword);然后与 $user 中存储的比较 -
@Edwin,我之前做过,生成的哈希不匹配。我明白虽然 bcrypt 每次都会生成不同的哈希值。 isPasswordValid() 方法应该使用相同的内置盐来检查匹配。在任何情况下我都按照你的建议做了,同样,它与来自 db 的哈希不同。
-
所以这意味着从我以前的
$tempPass开始,如果您在isPasswordValid上使用它应该可以工作(再次 - 仅用于调试目的:D) -
除了 isPasswordValid() 要求第一个参数是 UserInterface $user 的实例,而不是字符串。所以不能在那里插入 $tempPass。
标签: php symfony authentication login bcrypt