Symfony2 UserSecurityEncoder實現自己的驗證方式

mot發表於2014-04-19

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

相關文章