Symfony 3 bcrypt 密码无法验证

2024-01-15

我很可能错过了一些愚蠢的东西,但我在这方面花了相当多的时间,所以任何帮助都是值得赞赏的。

认证是基于本教程 https://knpuniversity.com/screencast/guard/install

我正在使用 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) "[email protected] /cdn-cgi/l/email-protection"
["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) "[email protected] /cdn-cgi/l/email-protection"
  ["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)

在埃德温给我指明了正确的方向之后,我成功地让这个工作成功了。事实上,加密并不是唯一的问题。 这些变化主要涉及注册控制器,其中修改了密码加密代码。 我还更改了现在基于的表单验证器this http://symfony.com/doc/current/security/guard_authentication.html

因为我的问题所指出的先前基础已经过时了。

最后,Symfony 不太喜欢 Ajax,因此 Ajax URL 进行了调整以适用于开发环境。

这是整个代码:

安全.yml

security:
encoders:
    UsedBundle\Entity\User: 
        algorithm: bcrypt
providers:
    db_provider:
        entity:
            class: UsedBundle:User
            property: email
            manager_name: used

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    main:
        anonymous: ~
        provider: db_provider
        form_login: 
            login_path: /
            username_parameter: _email
            check_path: /login_check
        guard:
            authenticators:
                - app.form_login_authenticator 
        logout:
            path:   /logout
            target: /
access_control:
    - { path: ^/admin, roles: ROLE_ADMIN }
    - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }

注册控制器的变化:

 if ($form->isSubmitted() && $form->isValid()) {
     $this->formData = $request->request->get($form->getName('user'));
     $this->plainPassword = $this->formData['plainPassword']['first'];
     $password = $this->get('security.password_encoder')
                ->encodePassword($user, $this->plainPassword );
  .....

新的验证器:

namespace UsedBundle\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Security;


class FormLoginAuthenticator extends AbstractGuardAuthenticator
{
private $container;

public function __construct(ContainerInterface $container)
{
    $this->container = $container;
}

public function getCredentials(Request $request)
{
    if ($request->getPathInfo() != '/login_check') {
        return;
    }
    $email = $request->request->get('_email');
    $request->getSession()->set(Security::LAST_USERNAME, $email);
    $password = $request->request->get('_password');
    return array(
        'email' => $email,
        'password' => $password
    );
}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    $email = $credentials['email'];
    return $this->user = $this->container
         ->get('doctrine')
         ->getRepository('UsedBundle:User', 'used')
         ->findOneByemail( $email );
}

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{
        return true;
    }
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    $session=$request->getSession();
    $session->set('seller_id', $token->getUser()->getId());
    $session->set('email', $token->getUser()->getEmail());
    return new JsonResponse(
        array(
            'userId' => $token->getUser()->getId(),
            'message' => $this->credentials,
            'statut' => 'ok',
            'roles' => $token->getUser()->getRoles(),
            'email' => $token->getUser()->getEmail(),
            )
    );

    // for non-AJAX requests, return the normal redirect
    //return parent::onAuthenticationSuccess($request, $token, $providerKey);
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    $data = array(
        'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

        // or to translate this message
        // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
    );

    return new JsonResponse($data, Response::HTTP_FORBIDDEN);
}

/**
 * Called when authentication is needed, but it's not sent
 */
public function start(Request $request, AuthenticationException $authException = null)
{

    $data = array(
        'message' => 'Authentication Required'
    );

    return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);

}

public function supportsRememberMe()
{
    return false;
}

}

登录控制器:

namespace UsedBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class LoginController extends Controller
{
/**
 * @Route("/login", name="login")
 */
public function loginAction(Request $request)
{
    $helper = $this->get('security.authentication_utils');
    return $this->render('common/login.html.twig', array(
        // last username entered by the user (if any)
        'last_username' => $helper->getLastUsername(),
        // last authentication error (if any)
        'error' => $helper->getLastAuthenticationError(),
    ));

}

/**
 * @Route("/login_check", name="security_login_check")
 */
public function loginCheckAction()
{
    // will never be executed
}
}

这就是开发中 Ajax url 的样子:]

            $.ajax({
            url: "/app_dev.php/login_check",
            type: "POST",
            dataType: "json",
            data: str,
            success: function(data) {
    .....
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Symfony 3 bcrypt 密码无法验证 的相关文章

随机推荐

  • Trie、后缀树、后缀数组

    哪种结构提供最佳的性能结果 trie 前缀树 后缀树还是后缀数组 还有其他类似的结构吗 这些结构的良好 Java 实现是什么 编辑 在这种情况下 我想在大型名称词典和大量自然语言文本之间进行字符串匹配 以便识别文本上词典的名称 特里树是第一
  • 在 chrome DevTools/Console 面板中复制文本无法正常工作

    描述错误 最近 在 macOS 版本 12 6 3 上使用 Chrome 版本 112 0 5615 49 时 我在从 DevTools 的控制台面板复制和粘贴时遇到了问题 选择一个单词并复制后 当我粘贴它时 它总是向后移动2个字符 这可能
  • 最好的 JavaScript 日期解析器和格式化器? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 使用 Zend_DB_Table 选择查询

    我有一个类似以下的代码 class Application Model Company extends Zend Db Table Abstract protected name companies private id private n
  • 为什么 rm 命令不删除文件? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 当我今天访问我的 Ubuntu 16 04 服务器并想要删除文件 test2 时 它根本没有被删除 我用过 rm test2 也 rm f
  • Nexus 7 (ME370T) 上的 BLE 与 Android 4.4.2

    我一直在尝试使用 sdk sdk samples android 18 legacy BluetoothLeGatt 中的示例将 BLE 设备与我的 Nexus 7 ME370T 配对 但我收到信息 不支持 Ble 我正在寻找解决方案 但我
  • XAML文件如何与cs文件关联?

    看来 XAML 文件在 C 项目中应该有相应的 cs 文件 我知道 Visual Studio 可以为我们做所有事情 我只是好奇它们是如何联系在一起的 我的意思是 它们是在项目文件中指定的 还是仅仅因为它们具有相同的名称 而且 App xa
  • 使用 Appium 测试 Android 应用程序时无法创建新的远程会话

    我正在尝试使用 Appium 在 Eclipse 中运行用 java 编码的测试脚本示例 我通过 npm 运行 Appium 我使用的是 Appium 1 6 3 我对 Appium 并不陌生 我之前在 Mac 和 Windows 上运行它
  • 以编程方式设置 java.util.logging 目标

    我使用 java util logging 进行日志记录和跟踪 如何在 Java 应用程序中动态设置应写入日志的文件 The java util logging FileHandler可能会为你完成它的工作 以下代码片段显示了如何以编程方式
  • if 表达式中的运算顺序是否发生变化?

    我最近遇到了一些我认为我马上就能理解的东西 但更多地思考它 我想理解它为什么会这样工作 考虑下面的代码 这 x 9 显然正在接受评估 而 y 11 不是 我的第一个想法是合乎逻辑的 启动 发现表达式已经变为 false 并在计算表达式的第二
  • 尝试部署 firebase 函数时出现 ESLint 错误

    我尝试部署 firebase 函数 但由于 ESLint 的一些问题 它一直失败 我也尝试过谷歌搜索答案 但我看到的一切对我来说都是希腊语 我也偶然发现this https stackoverflow com questions 47852
  • 如何将 CSharpEntityTypeGenerator 拉入项目?

    我看过很多帖子讨论如何子类化CSharpEntityTypeGenerator修改 EF Core 写出的内容 Visual Studio 不喜欢这样并要求安装Microsoft EntityFrameworkCore Design 我已经
  • 需要类或命名空间

    我得到了 C 中枚举的编译时间 错误显示 Expected a class or namespace mf setStatus MediaFile SyncStatus Synced 枚举是这样定义的 class MediaFile pub
  • 是否可以在 apk 中获得对 sqlite 数据库的只读访问权限? [复制]

    这个问题在这里已经有答案了 可能的重复 如何将现有数据库放入 apk 文件中 https stackoverflow com questions 4022866 how to put existing database in the apk
  • Python:字符串列表中子字符串的最佳搜索

    我有一个特殊的问题 我想在许多字符串列表中搜索许多子字符串 以下是我想做的事情的要点 listStrings ACDE CDDE BPLL listSubstrings ACD BPI KLJ 上述条目只是示例 len listString
  • 授予 IIS Express 访问 VMWare 中网络驱动器的权限

    我在 VMWare 中有一个 Windows 7 虚拟机 用于使用默认的 IIS Express 服务器开发 ASP NET MVC 5 Web 应用程序 我喜欢将项目保存在外部硬盘驱动器上 我可以通过共享文件夹 网络驱动器在虚拟机中访问该
  • 我可以仅使用泛型而不是引用类型吗?

    在编写 Map 代码时 我发现声明Map
  • 将 iTextSharp PDF 作为内存流返回会导致 StreamNotSupported

    我正在使用 iTextSharp 中的 PdfStamper 创建 PDF 文件 并将 PDF 作为内存流返回 调用函数的对象 然后用于在 Teleriks PDF Viewer Component for WinForms 中显示 PDF
  • 如何在opencv-python中创建透明遮罩

    我有白色背景的标志 任意形状的标志 图像 我想获得具有透明背景的标志图像 我已经成功创建了一个蒙版并将其应用到图像上 并认为使蒙版透明是可行的 我在这里和其他地方进行了很多搜索 但没有什么真正对我有帮助 import cv2 import
  • Symfony 3 bcrypt 密码无法验证

    我很可能错过了一些愚蠢的东西 但我在这方面花了相当多的时间 所以任何帮助都是值得赞赏的 认证是基于本教程 https knpuniversity com screencast guard install 我正在使用 bcrypt 对密码进行