我使用Silex框架,特别是SecurityServiceProvider。
我必须创建自己的 User 类(因为我的盐是用户名 => 默认类盐为 null):
<?php
namespace Adh\Security;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
class User implements AdvancedUserInterface {
private $username;
private $password;
public function __construct($username, $password)
{
$this->username = $username;
$this->password = $password;
}
public function getRoles()
{
return array();
}
public function getPassword()
{
return $this->password;
}
public function getSalt()
{
return $this->username;
}
...
}
到目前为止,没有问题。现在,我必须创建一个自定义 UserProvider 来从 MySQL 检索我的用户:
<?php
namespace Adh\Security;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Doctrine\DBAL\Connection;
class UserProvider implements UserProviderInterface
{
private $conn;
public function __construct(Connection $conn)
{
$this->conn = $conn;
}
public function loadUserByUsername($username)
{
$stmt = $this->conn->executeQuery('SELECT * FROM account WHERE username like ?', array($username));
if (!$user = $stmt->fetch()) {
throw new UsernameNotFoundException(sprintf('Le nom d\'utilisateur "%s" n\'existe pas', $username));
}
return new \Adh\Security\User($user['username'], $user['sha_pass_hash']);
}
...
}
并注册安全提供程序:
$app->register(new Silex\Provider\SecurityServiceProvider(), array(
'security.firewalls' => array(
'user' => array(
'pattern' => '^/user',
'form' => array('login_path' => '/connexion', 'check_path' => '/user'),
'users' => $app->share(function () use ($app) {
return new Adh\Security\UserProvider($app['db']);
})
)
)
));
$app['security.encoder_factory'] = $app->share(function ($app) {
return new EncoderFactory(
array('Adh\Security\User' => new Adh\Security\PasswordEncoder())
);
});
它有效,除非身份验证是肯定的(用户名和密码匹配)我有这个异常(exception):
RuntimeException: There is no user provider for user "Adh\Security\User".
如何为我的 User 类设置 UserProvider ?
谢谢
最佳答案
我找到了解决方案。为了创建我的提供程序,我遵循了以下示例:http://silex.sensiolabs.org/doc/providers/security.html#defining-a-custom-user-provider
在refreshUser方法中:
if (!$user instanceof User) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}
这对于默认的 User 类是正确的:我有自己的 User 类,因此会引发异常。
条件变为:
if (!$user instanceof \Adh\Security\User) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}
关于php - Silex框架: Create an UserProvider/PasswordEncoder/User,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19867899/