php 使用symfony 6.2在md5中散列密码

eimct9ow  于 2023-03-07  发布在  PHP
关注(0)|答案(1)|浏览(148)

我目前正在做一个项目,目标是用Symfony从一个繁重的Java应用程序转移到一个Web应用程序。
目标是从现有数据库开始,而根本不修改它。
在这个数据库中,密码是用md5散列的,经过几个星期的麻烦,我无法改变symfony的散列系统来使用md5。
我已经做了几个测试,对于这一行,密码被很好地散列了:哈希("md5",$密码);
只是,我希望散列可以自动完成,就像在基本的symfony中一样。所以我按照symfony文档,尝试在secutiry.yaml中添加以下代码行:密码哈希器(_H):应用程序哈希器:ID:"应用程序\安全\哈希程序\自定义安全哈希程序"
因此,指向按如下方式填写的CustomVerySecureHasher文件:

class CustomVerySecureHasher implements PasswordHasherInterface
{
    public function hash(string $plainPassword): string
    {
        // Check if the MD5 hash algorithm is supported
        if (!in_array('md5', hash_algos(), true)) {
            throw new Exception('MD5 is not supported by this system.');
        }

        // Hash the password using the MD5 algorithm
        return md5($plainPassword);
    }

    public function verify(string $hashedPassword, string $plainPassword): bool
    {
        // Compare the hashed password with the MD5 hashed plaintext password
        return $hashedPassword === md5($plainPassword);
    }

    public function needsRehash(string $hashedPassword): bool
    {
        // There is no need to rehash with MD5, as it is considered insecure
        return false;
    }
}

不幸的是,这似乎不起作用。我尝试了多种解决方案,但都不起作用。
下面是我的AppCustomAuthenticator类的外观(由php bin/console make:auth命令生成):

class AppCustomAuthenticator extends AbstractLoginFormAuthenticator
{
    use TargetPathTrait;

    public const LOGIN_ROUTE = 'app_login';

    public function __construct(private UrlGeneratorInterface $urlGenerator)
    {
    }

    public function authenticate(Request $request): Passport
    {
        $email = $request->request->get('login', '');

        $request->getSession()->set(Security::LAST_USERNAME, $email);

//        $password = $request->request->get('password', '');
//        $test = hash('md5', $password);
//        dd($test);

        return new Passport(
            new UserBadge($email),
            new PasswordCredentials($request->request->get('password', '')),
            [
                new CsrfTokenBadge('authenticate', $request->request->get('_csrf_token')),
            ]
        );
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
            return new RedirectResponse($targetPath);
        }

        // For example:
        // return new RedirectResponse($this->urlGenerator->generate('some_route'));
        throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
    }

    protected function getLoginUrl(Request $request): string
    {
        return $this->urlGenerator->generate(self::LOGIN_ROUTE);
    }
}

我已经测试了几次,我从我的表单中得到了我的登录名和密码,没有任何问题。确实,哈希阶段是问题所在。
下面是我在安全控制器中的登录方法:

#[Route(path: '/', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils): Response
{
    // if ($this->getUser()) {
    //     return $this->redirectToRoute('target_path');
    // }

    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();
    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();
//        if ($lastUsername) {
//            dd($lastUsername);
//        }

    return $this->render('/security/login.html.twig', ['login' => $lastUsername, 'error' => $error]);
}

[编辑]:以下是我的security. yaml文件的内容:

security:
    password_hashers:
        App\Entity\Useraccount:
            id: 'App\Security\Hasher\CustomVerySecureHasher'
    providers:
        users_in_memory: { memory: null }
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            lazy: true
            provider: users_in_memory
            custom_authenticator: App\Security\AppCustomAuthenticator
access_control:

when@test:
    security:
        password_hashers:
            Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
                algorithm: auto
                cost: 4 # Lowest possible value for bcrypt
                time_cost: 3 # Lowest possible value for argon
                memory_cost: 10 # Lowest possible value for argon

有人有什么想法吗?
我用的是php 8.1和symfony 6.2

vltsax25

vltsax251#

已经有一段时间没有看到这些问题了,Symfony 6确实在布线上做了一些改变。加上文档相当冗长,不是超级清晰。你应该遵循密码哈希。

# config/packages/security.yaml
security:
    # https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
    password_hashers:
        # Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
        App\Entity\User:
            id: 'App\Security\MyExtremelyInSecureHasher'

使用以下设备测试接线:

$ bin/console security:hash-password password

Symfony Password Hash Utility
=============================

 --------------- ---------------------------------- 
  Key             Value                             
 --------------- ---------------------------------- 
  Hasher used     App\Security\MyExtremelyInSecureHasher            
  Password hash   5f4dcc3b5aa765d61d8327deb882cf99  
 --------------- ----------------------------------

配置上有很多变化。可能根本不需要自定义哈希器,但使用一个也无妨。当然,一旦一切正常,你就可以设置自动迁移到一个更安全的哈希器。
如果您仍然有问题,请使用security.yaml文件的相关内容更新您的问题。

相关问题