我正在关注Symfony书籍和食谱谱,我遇到了简单登录表格的问题 - 无论输入的登录/通行证是否有效,消息是否显示 - '凭证无效'。用户通过Doctrine(实现UserInterface的User类)加载。源代码:
安全档案:
providers:
user_provider:
entity:
class: BakaMainBundle:User
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
default:
anonymous: ~
http_basic: ~
provider: user_provider
form_login:
login_path: /login
check_path: /login_check
target_path_parameter: /index/welcome
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
encoders:
Baka\MainBundle\Entity\User:
algorithm: bcrypt
cost: 12
控制器:
class SecurityController extends Controller
{
/**
* @Route("/login", name="login_route")
*/
public function loginAction()
{
$authUtils = $this->get('security.authentication_utils');
$error = $authUtils->getLastAuthenticationError();
$enteredUsername = $authUtils->getLastUsername();
return $this->render('BakaMainBundle::Login.html.twig',
array
(
'last_username' => $enteredUsername,
'error' => $error,
'site' => 'login'
));
}
/**
* @Route("/login_check", name="login_check")
*/
public function loginCheckAction()
{
}
}
用户存储库:
class UserRepository extends \Doctrine\ORM\EntityRepository implements UserProviderInterface
{
public function loadUserByUsername($username)
{
$user = $this->createQueryBuilder('u')
->where('u.username = :username OR u.email = :email')
->setParameter('username', $username)
->setParameter('email', $username)
->getQuery()
->getOneOrNullResult();
if ($user === null)
{
$returnMessage = sprintf(
'%s - such username of email adress does not exist in database! Try again with other login data.',
$username);
throw new UnsupportedUserException($returnMessage);
}
return $user;
}
public function refreshUser(UserInterface $user)
{
$userClass = get_class($user);
if (!$this->supportsClass($userClass))
{
throw new UnsupportedUserException
(sprintf('Ops! Something goes wrong. Your user class is not supported by security system.'));
}
return $this->find($user->getId());
}
public function supportsClass($userclass)
{
return $this->getEntityName() === $userclass || is_subclass_of($userclass, $this->getEntityName());
}
表格html标签:
<form action="{{ path('login_check') }}" method="post">
有什么建议吗?我将很感激解决我的问题。
答案 0 :(得分:1)
我认为在指定提供程序类时应该使用类命名空间而不是包名称。此外,您需要指定要从property
中选择哪个Entity
作为“用户名”:
security:
providers:
user_provider:
entity:
class: Baka\MainBundle\Entity\User
property: username (this should be an existing property of your entity class)
此外,您的User
实体需要实施Symfony\Component\Security\Core\User\UserInterface
(或AdvancedUserInterface
)。完成后,如果您的数据库中的用户使用正确编码的密码,那么一切都应该有效。
你应该阅读:
答案 1 :(得分:0)
我已经确定了问题的原因,并且发现它是微不足道的 - 在DB中用作编码密码行的字段有15个字符的长限制:
ClassRegister cr1= new ClassRegister ("Ron", "T09")
由于“12轮”bcrypt需要更多数字来表示普通密码,因此Doctrine被迫缩短加密传递,因此以后无法解码。更改为Symfony大小建议后问题已经消失:
/**
* @ORM\Column(type="string", length=15)
*/
protected $password;
感谢您的支持。