Symfony2 UserSecurityEncoder实现自己的验证方式

fosuserbundle默认使用sha512加密

如果要实现自己的加密方式 需要继承Symfony\Component\Security\Core\Encoder\BasePasswordEncoder

 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.encoder

done

你可能感兴趣的:(fosuserbundle,symfony)