本文介绍了Symfony 2认证(doctrine)实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我已经尝试所有关于身份验证的所有代码
(doctrine)实体在 2.我不能让它工作。
当我使用in_memory提供程序的所有工作正常。
我正在使用PR8。



我的 security.yml

 安全性:
编码器:
合作伙伴\FrontendBundle\Entity\User:明文
Symfony\Component\\ \\ Security\Core\User\User:plaintext
providers:
main:
entity:{class:FrontendBundle:User,property:username}
#in_memory:
#users:
#sergi:{password:boo123,roles:['ROLE_USER']}
防火墙:
main:
pattern:/.*
form_login:true
anonymous:true
logout:true
access_control:
- {path:/docs.*,role:ROLE_USER}
- {path:/控制*,角色:ROLE_USER}
- {path:/.*,role:IS_AUTHENTICATED_ANONYMOUSLY}
role_hierarchy:
ROLE_ADMIN:ROLE_USER

我的用户实体

 <?php 
命名空间合作伙伴\FrontendBundle\Entity;
使用Symfony\Component\Security\Core\User\UserInterface;
使用合作伙伴\FrontendBundle\Repository\UserRepository;
/ **
* @orm:Entity(repositoryClass =Partners\FrontendBundle\Repository
\UserRepository)
* @orm:Table(name =users )
* /
class用户实现UserInterface
{
/ **
* @orm:Id
* @orm:Column(type =整数)
* @orm:GeneratedValue(strategy =IDENTITY)
* /
protected $ id;
/ **
* @orm:列(type =string,length =32,unique = true)
* /
protected $ username;
/ **
* @orm:列(type =string,length =255,unique = true)
* /
protected $ email;
/ **
* @orm:Column(type =string,length =128)
* /
protected $ password;
/ **
* @orm:Column(type =string,length =128)
* /
protected $ organization;
/ **
* @orm:Column(type =string,length =128)
* /
protected $ contact;
/ **
* @orm:列(type =string,length =16)
* /
protected $ phone;
/ **
* @orm:Column(type =string,length =10)
* /
protected $ cid;
/ **
* @orm:Column(type =smallint)
* /
protected $ status;
public function getId()
{
return $ this-> id;
}
public function setId($ id)
{
$ this-> id = $ id;
}
public function getUsername()
{
return $ this-> username;
}
public function setUsername($ username)
{
$ this-> username = $ username;
}
public function getPassword()
{
return $ this-> password;
}
public function setPassword($ password)
{
$ this-> password = $ password;
}
public function setEmail($ email)
{
$ this-> email = $ email;
}
public function getEmail()
{
return $ this-> email;
}
public function setPhone($ phone)
{
$ this-> phone = $ phone;
}
public function getPhone()
{
return $ this-> phone;
}
public function setContact($ contact)
{
$ this-> contact = $ contact;
}
public function getContact()
{
return $ this-> contact;
}
public function setOrganization($ org)
{
$ this-> organization = $ org;
}
public function getOrganization()
{
return $ this-> organization;
}
public function setCid($ cid)
{
$ this-> cid = $ cid;
}
public function getCid()
{
return $ this-> cid;
}
public function setStatus($ status)
{
$ this-> status = $ status;
}
public function getStatus()
{
return $ this-> status;
}
/ **
*实现UserInterface界面
* /
public function __toString()
{
return $ this-> ; getUsername();
}
public function getRoles()
{
return array('ROLE_USER');
}
public function eraseCredentials()
{
return false;
}
public function getSalt()
{
return $ this-> getId();
}
/ **
*等于。
*
* @param UserInterface $ account
* @return bool
* /
public function equals(UserInterface $ account)
{
if($ account-> getUsername()!= $ this-> getUsername){
return false;
}
if($ account-> getEmail()!= $ this-> getEmail){
return false;
}
返回true;
}
}

UserRepository

 <?php 
命名空间合作伙伴\FrontendBundle\Repository;
使用Doctrine\ORM\EntityRepository;
使用Symfony\Component\Security\Core\User\UserProviderInterface;
使用Symfony\Component\Security\Core\User\UserInterface;
class UserRepository extends EntityRepository implements
UserProviderInterface
{
const CREATED = 0;
const ACTIVE = 10;
const INACTIVE = 20;
/ **
* loadUserByUsername。
*
* @param string $ username
* @return Partners\FrontendBundle\Entity\User
* /
public function loadUserByUsername($ username)
{
return $ this-> findOneBy(array('username'=> $ username));
}
函数loadUser(UserInterface $ user)
{
return $ user;
}
函数loadUserByAccount(AccountInterface $ account)
{
return $ this-> loadUserByUsername($ account-> getUsername());
}
公共职能supportsClass($类)
{
返回真;
}
}

当我填充登录形成在$错误误差= $这 - >的get( '请求') - >的getSession() - >得到(SecurityContext的:: AUTHENTICATION_ERROR);是:

  exception'Symfony\Component\Security\Core\Exception 
\BadCredentialsException'with / var / www /
启发/中继/ Symfony / vendor / symfony / src / Symfony /组件/安全/
核心/身份验证/提供程序/ DaoAuthenticationProvider.php:66堆栈
trace:#0 / var / www / inspiring / trunk / Symfony / vendor / symfony / src / Symfony /
组件/ HttpFoundation / SessionStorage / NativeSessionStorage.php(81):
session_start #1 / var / www / inspiring / trunk / Symfony / app / cache / dev /
classes-53824.php(284):Symfony\Component\HttpFoundation\SessionStorage
\NativeSessionStorage- > start()#2 / var / www / inspiring / trunk / Symfony / app /
cache / dev / appDevDebugProjectContainer.php(1151):Symfony\Component
\HttpFoundation\Session- > start()#3 / var / www / inspiring / trunk / Symfony /
app / bootstrap.php.cache(109):appDevDebugProjectContainer-
> getSessionService() 4 / var / www / inspiring / trunk / Symfony / app / cache / dev /

classes-53824.php(1553):Symfony\Component\DependencyInjection
\Container- > get('session')#5 / var / www / inspiring / trunk / Symfony / app /
cache / dev / classes-53824.php(1544):Symfony\Bundle\FrameworkBundle
\RequestListener-> initializeSession(Object(Symfony\Component
\HttpFoundation\Request),true)#6 / var / www / inspiring / trunk / Symfony /
app / cache / dev / classes-53824.php(1214):Symfony\Bundle\FrameworkBundle
\RequestListener-> onCoreRequest(Object(Symfony\Component\HttpKernel
\Event\GetResponseEvent) )#7 / var / www / inspiring / trunk / Symfony / vendor /
symfony / src / Symfony / Bundle / FrameworkBundle / Debug /
TraceableEventDispatcher.php(49):Symfony\Component\EventDispatcher
\EventDispatcher-> triggerListener(Object(Symfony\Bundle\FrameworkBundle
\RequestListener),'onCoreReque st',Object(Symfony\Component\HttpKernel
\Event\GetResponseEvent))#8 / var / www / inspiring / trunk / Symfony / app /
cache / dev / classes-53824 .php(1146):Symfony\Bundle\FrameworkBundle\Debug
\TraceableEventDispatcher-> triggerListener(Object(Symfony\Bundle
\FrameworkBundle\RequestListener),'onCoreRequest' Object(Symfony
\Component\HttpKernel\Event\GetResponseEvent))#9 / var / www / inspiring /
trunk / Symfony / app / cache / dev / classes-53824.php 1734):Symfony\Component
\EventDispatcher\EventDispatcher-> dispatch('onCoreRequest',
Object(Symfony\Component\HttpKernel\Event\GetResponseEvent))#10 / var /
www / inspiring / trunk / Symfony / app / bootstrap.php.cache(411):Symfony
\Bundle\FrameworkBundle\ContainerAwareEventDispatcher-
> dispatch('onCoreRequest ,对象(Symfony\Component\HttpKernel\Event

\GetResponseEvent))#11 / var / www / inspiring / trunk / Symfony / app /
bootstrap.php.cache(400):Symfony\Component\HttpKernel \HttpKernel-
> handleRaw(Object(Symfony\Component\HttpFoundation\Request),1)#12 /

var / www / inspiring / trunk / Symfony / vendor / symfony / src / Symfony / Bundle /
FrameworkBundle / HttpKernel.php(35):Symfony\Component\HttpKernel
\HttpKernel-> handle(Object(Symfony\Component\HttpFoundation\Request),
1,true)#13 / var / www / inspiring / trunk / Symfony / app /
bootstrap.php.cache(576):Symfony\Bundle\FrameworkBundle\HttpKernel-
> handle(Object(Symfony\Component\HttpFoundation\Request),1,true)

#14 /var/www/inspiring/trunk/Symfony/web/app_dev.php(15): Symfony
\Component\HttpKernel\Kernel-> handle(Object(Symfony\Component
\HttpFoundation\Request))#15 {main}

我不知道问题出在哪里都可以。


解决方案

最后有人帮了我。
问题是我没有使用任何盐来创建密码,而在User类的getSalt函数中,我正在返回ID。



密码是这样生成的(在控制器中):

  $ factory = $ this-> container-> get 'security.encoder_factory'); 
$ encoder = $ factory-> getEncoder($ user);
$ pwd = $ encoder-> encodePassword('your_random_password',$ user-> getSalt());
$ user-> setPassword($ pwd);


I think I've tried all code in all posts about authentication with(doctrine) Entity in Symfony 2. And I can`t make it work.When I use in_memory provider all works fine.I'm using the PR8.

My security.yml

security:
    encoders:
        Partners\FrontendBundle\Entity\User:       plaintext
        Symfony\Component\Security\Core\User\User: plaintext
    providers:
        main:
            entity: { class: FrontendBundle:User, property: username }
        #        in_memory:
        #            users:
        #                sergi:        { password: boo123, roles: [ 'ROLE_USER' ] }
    firewalls:
        main:
            pattern:         /.*
            form_login:      true
            anonymous:       true
            logout:          true
    access_control:
        - { path: /docs.*, role: ROLE_USER }
        - { path: /control.*, role: ROLE_USER }
        - { path: /.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER

My User entity

<?php
    namespace Partners\FrontendBundle\Entity;
    use Symfony\Component\Security\Core\User\UserInterface;
    use Partners\FrontendBundle\Repository\UserRepository;
    /**
     * @orm:Entity(repositoryClass="Partners\FrontendBundle\Repository
    \UserRepository")
     * @orm:Table(name="users")
     */
    class User implements UserInterface
    {
        /**
         * @orm:Id
         * @orm:Column(type="integer")
         * @orm:GeneratedValue(strategy="IDENTITY")
         */
        protected $id;
        /**
         * @orm:Column(type="string", length="32", unique=true)
         */
        protected $username;
        /**
         * @orm:Column(type="string", length="255", unique=true)
         */
        protected $email;
        /**
         * @orm:Column(type="string", length="128")
         */
        protected $password;
        /**
         * @orm:Column(type="string", length="128")
         */
        protected $organization;
        /**
         * @orm:Column(type="string", length="128")
         */
        protected $contact;
        /**
         * @orm:Column(type="string", length="16")
         */
        protected $phone;
        /**
         * @orm:Column(type="string", length="10")
         */
        protected $cid;
        /**
         * @orm:Column(type="smallint")
         */
        protected $status;
        public function getId()
        {
            return $this->id;
        }
        public function setId($id)
        {
            $this->id = $id;
        }
        public function getUsername()
        {
            return $this->username;
        }
        public function setUsername($username)
        {
            $this->username = $username;
        }
        public function getPassword()
        {
            return $this->password;
        }
        public function setPassword($password)
        {
            $this->password = $password;
        }
        public function setEmail($email)
        {
            $this->email = $email;
        }
        public function getEmail()
        {
            return $this->email;
        }
        public function setPhone($phone)
        {
            $this->phone = $phone;
        }
        public function getPhone()
        {
            return $this->phone;
        }
        public function setContact($contact)
        {
            $this->contact = $contact;
        }
        public function getContact()
        {
            return $this->contact;
        }
        public function setOrganization($org)
        {
            $this->organization = $org;
        }
        public function getOrganization()
        {
            return $this->organization;
        }
        public function setCid($cid)
        {
            $this->cid = $cid;
        }
        public function getCid()
        {
            return $this->cid;
        }
        public function setStatus($status)
        {
          $this->status = $status;
        }
        public function getStatus()
        {
          return $this->status;
        }
        /**
         * Implementing the UserInterface interface
         */
        public function __toString()
        {
            return $this->getUsername();
        }
        public function getRoles()
        {
            return array('ROLE_USER');
        }
        public function eraseCredentials()
        {
            return false;
        }
        public function getSalt()
        {
            return $this->getId();
        }
        /**
         * equals.
         *
         * @param UserInterface $account
         * @return bool
         */
        public function equals(UserInterface $account)
        {
            if ($account->getUsername() != $this->getUsername) {
                return false;
            }
            if ($account->getEmail() != $this->getEmail) {
                return false;
            }
            return true;
        }
    }

The UserRepository

<?php
    namespace Partners\FrontendBundle\Repository;
    use Doctrine\ORM\EntityRepository;
    use Symfony\Component\Security\Core\User\UserProviderInterface;
    use Symfony\Component\Security\Core\User\UserInterface;
    class UserRepository extends EntityRepository implements
    UserProviderInterface
    {
        const CREATED  = 0;
        const ACTIVE   = 10;
        const INACTIVE = 20;
        /**
         * loadUserByUsername.
         *
         * @param string $username
         * @return Partners\FrontendBundle\Entity\User
         */
        public function loadUserByUsername($username)
        {
            return $this->findOneBy(array('username' => $username));
        }
        function loadUser(UserInterface $user)
        {
            return $user;
        }
        function loadUserByAccount(AccountInterface $account)
        {
            return $this->loadUserByUsername($account->getUsername());
        }
        public function supportsClass($class)
        {
            return true;
        }
    }

When I fill the login form the error in the $error = $this->get('request')->getSession()->get(SecurityContext::AUTHENTICATION_ERROR); is:

exception 'Symfony\Component\Security\Core\Exception
\BadCredentialsException' with message 'Bad credentials' in /var/www/
inspiring/trunk/Symfony/vendor/symfony/src/Symfony/Component/Security/
Core/Authentication/Provider/DaoAuthenticationProvider.php:66 Stack
trace: #0 /var/www/inspiring/trunk/Symfony/vendor/symfony/src/Symfony/
Component/HttpFoundation/SessionStorage/NativeSessionStorage.php(81):
session_start() #1 /var/www/inspiring/trunk/Symfony/app/cache/dev/
classes-53824.php(284): Symfony\Component\HttpFoundation\SessionStorage
\NativeSessionStorage->start() #2 /var/www/inspiring/trunk/Symfony/app/
cache/dev/appDevDebugProjectContainer.php(1151): Symfony\Component
\HttpFoundation\Session->start() #3 /var/www/inspiring/trunk/Symfony/
app/bootstrap.php.cache(109): appDevDebugProjectContainer-
>getSessionService() #4 /var/www/inspiring/trunk/Symfony/app/cache/dev/

classes-53824.php(1553): Symfony\Component\DependencyInjection
\Container->get('session') #5 /var/www/inspiring/trunk/Symfony/app/
cache/dev/classes-53824.php(1544): Symfony\Bundle\FrameworkBundle
\RequestListener->initializeSession(Object(Symfony\Component
\HttpFoundation\Request), true) #6 /var/www/inspiring/trunk/Symfony/
app/cache/dev/classes-53824.php(1214): Symfony\Bundle\FrameworkBundle
\RequestListener->onCoreRequest(Object(Symfony\Component\HttpKernel
\Event\GetResponseEvent)) #7 /var/www/inspiring/trunk/Symfony/vendor/
symfony/src/Symfony/Bundle/FrameworkBundle/Debug/
TraceableEventDispatcher.php(49): Symfony\Component\EventDispatcher
\EventDispatcher->triggerListener(Object(Symfony\Bundle\FrameworkBundle
\RequestListener), 'onCoreRequest', Object(Symfony\Component\HttpKernel
\Event\GetResponseEvent)) #8 /var/www/inspiring/trunk/Symfony/app/
cache/dev/classes-53824.php(1146): Symfony\Bundle\FrameworkBundle\Debug
\TraceableEventDispatcher->triggerListener(Object(Symfony\Bundle
\FrameworkBundle\RequestListener), 'onCoreRequest', Object(Symfony
\Component\HttpKernel\Event\GetResponseEvent)) #9 /var/www/inspiring/
trunk/Symfony/app/cache/dev/classes-53824.php(1734): Symfony\Component
\EventDispatcher\EventDispatcher->dispatch('onCoreRequest',
Object(Symfony\Component\HttpKernel\Event\GetResponseEvent)) #10 /var/
www/inspiring/trunk/Symfony/app/bootstrap.php.cache(411): Symfony
\Bundle\FrameworkBundle\ContainerAwareEventDispatcher-
>dispatch('onCoreRequest', Object(Symfony\Component\HttpKernel\Event

\GetResponseEvent)) #11 /var/www/inspiring/trunk/Symfony/app/
bootstrap.php.cache(400): Symfony\Component\HttpKernel\HttpKernel-
>handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1) #12 /

var/www/inspiring/trunk/Symfony/vendor/symfony/src/Symfony/Bundle/
FrameworkBundle/HttpKernel.php(35): Symfony\Component\HttpKernel
\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request),
1, true) #13 /var/www/inspiring/trunk/Symfony/app/
bootstrap.php.cache(576): Symfony\Bundle\FrameworkBundle\HttpKernel-
>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)

#14 /var/www/inspiring/trunk/Symfony/web/app_dev.php(15): Symfony
\Component\HttpKernel\Kernel->handle(Object(Symfony\Component
\HttpFoundation\Request)) #15 {main}

I don't know where the problem can be.

解决方案

Finally somebody helped me.The issue is that I wasn't using any salt to create the password, and in the getSalt function of the User class I was returning the ID.

The password is generated like this (in the controller):

$factory = $this->container->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$pwd = $encoder->encodePassword('your_random_password', $user->getSalt());
$user->setPassword($pwd);

这篇关于Symfony 2认证(doctrine)实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 21:06