首页 > 代码库 > Symfony2 UserSecurityEncoder实现自己的验证方式

Symfony2 UserSecurityEncoder实现自己的验证方式

fosuserbundle默认使用sha512加密如果要实现自己的加密方式 需要继承Symfony\Component\Security\Core\Encoder\BasePasswordEncoder<?phpnamespace Mc\AdminBundle\Security\Encoder;use Symfony\Component\Security\Core\Encoder\BasePasswordEncoder;use Symfony\Component\SecurityCore\Exception\BadCredentialsException;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: Mc\AdminBundle\Security\Encoder\JoomlaPasswordEncoder        arguments: [6]也可以在DependencyInjection/Configuration.php中添加参数:        $rootNode->children()                    ->scalarNode(‘cost‘)->defaultValue(6)->end()                    ->end()        ;最后在app/config/security.yml中设置自己的加密方式 这里用户组件是FOSUserBundle:security:    encoders:        Symfony\Component\Security\Core\User\User: plaintext        FOS\UserBundle\Model\UserInterface:            id: mc_user.security.core.encoder这里的id是service名 即 mc_user.encoderdone

 

Symfony2 UserSecurityEncoder实现自己的验证方式