Symfony2 UserSecurityEncoder实现自己的验证方式

fosuserbundle默认使用sha512加密

如果要实现自己的加密方式 需要继承SymfonyComponentSecurityCoreEncoderBasePasswordEncoder

<?php

namespace McAdminBundleSecurityEncoder;

use SymfonyComponentSecurityCoreEncoderBasePasswordEncoder;
use SymfonyComponentSecurityCoreExceptionBadCredentialsException;

class JoomlaPasswordEncoder extends BasePasswordEncoder
{
    private $cost;

    public function __construct( $cost)
    {
        $cost = intval( $cost);
        if( $cost < 4 || $cost > 31 )
        {
            throw new InvalidArgumentException('Cost too long , it must be in the range of 4-31');
        }
        $this->cost = sprintf('%02d' , $cost);
    }

    public function encodePassword( $raw , $salt = null )
    {
        if( $this->isPasswordTooLong($raw) )
        {
            throw new BadCredentialsException('Invalid password.');
        }
        return md5( md5( $raw ) . $salt );
    }

    public function isPasswordValid($encoded, $raw, $salt = null)
    {
        if ($this->isPasswordTooLong($raw)) 
        {
            return false;
        }


        return md5( md5( $raw).$salt) === $encoded;
    }
}
然后写入service

在bundle下面的Resources/config/services.yml(或者xml)添加一个服务:

    mc_user.security.core.encoder:
        class: McAdminBundleSecurityEncoderJoomlaPasswordEncoder
        arguments: [6]
也可以在DependencyInjection/Configuration.php中添加参数:

        $rootNode->children()
                    ->scalarNode('cost')->defaultValue(6)->end()
                    ->end()
        ;
最后在app/config/security.yml中设置自己的加密方式 这里用户组件是FOSUserBundle:

security:
    encoders:
        SymfonyComponentSecurityCoreUserUser: plaintext
        FOSUserBundleModelUserInterface:
            id: mc_user.security.core.encoder
这里的id是service名 即 mc_user.encoder

done
原文地址:https://www.cnblogs.com/huidaoli/p/3980497.html