我正在尝试制作广告系统。
class Advert {
protected $password;
}
要获得访问权限,用户应提供其广告的密码,而不是密码帐户。 但是如何使用Symfony2安全框架来编码和检查密码呢?
答案 0 :(得分:6)
在Symfony 2.6中可能版本较少:
$user = new User();// you object \Acme\DemoBundle\Entity\User from database
$hash = $this->get('security.password_encoder')->encodePassword($user, 'user password');
$user->setPassword($hash);
if( $this->get('security.password_encoder')->isPasswordValid($user, 'user password') ){
echo 'password equal';
}
答案 1 :(得分:3)
namespace Acme\TestBundle\Service;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
class Sha256Salted implements PasswordEncoderInterface
{
public function encodePassword($raw, $salt)
{
return hash('sha256', $salt . $raw); // Custom function for encrypt with sha256
}
public function isPasswordValid($encoded, $raw, $salt)
{
return $encoded === $this->encodePassword($raw, $salt);
}
}
这就是你如何使用它:
$advert->setSalt(uniqid(mt_rand())); // Unique salt
// Set encrypted password
$encoder = $this->container->get('acme.test.sha256salted_encoder')
->getEncoder($advert);
$password = $encoder->encodePassword('MyPass', $advert->getSalt());
$advert->setPassword($password);