发布于 2015-01-26 05:57:24 | 497 次阅读 | 评论: 0 | 来源: PHPERZ

这里有新鲜出炉的Symfony2教程,程序狗速度看过来!

Symfony开源的PHP开发框架

Symfony是一个基于MVC模式的面向对象的PHP5框架。Symfony允许在一个web应用中分离事务控制,服务逻辑和表示层。


本文为大家讲解的是Symfony2 使用UserSecurityEncoder实现自己的验证方式的示例,感兴趣的同学参考下.

fosuserbundle默认使用sha512加密

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

<?php

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



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务