Symfony2使用自定义实体提供程序ERROR对某人进行身份验证

时间:2012-06-16 01:15:59

标签: php symfony user-management

我在尝试实施自定义实体提供程序进行用户身份验证时遇到了问题。我得到了Mapping Exception,我的实体不是有效的或映射的超类。这是我的实际错误:      -------------异常/错误开始--------------

1/1 MappingException: Class MunichInnovationGroup\PatentBundle\Entity\UmUsers is not a valid entity or mapped super class.

in C:\wamp\www\idp\vendor\doctrine\lib\Doctrine\ORM\Mapping\MappingException.php line 142
at MappingException::classIsNotAValidEntityOrMappedSuperClass() in C:\wamp\www\idp\vendor\doctrine\lib\Doctrine\ORM\Mapping\Driver\DriverChain.php line 80
at DriverChain->loadMetadataForClass() in C:\wamp\www\idp\vendor\doctrine\lib\Doctrine\ORM\Mapping\ClassMetadataFactory.php line 281
at ClassMetadataFactory->loadMetadata() in C:\wamp\www\idp\vendor\doctrine\lib\Doctrine\ORM\Mapping\ClassMetadataFactory.php line 170
at ClassMetadataFactory->getMetadataFor() in C:\wamp\www\idp\vendor\doctrine\lib\Doctrine\ORM\EntityManager.php line 257
at EntityManager->getClassMetadata() in C:\wamp\www\idp\vendor\doctrine\lib\Doctrine\ORM\EntityManager.php line 573
at EntityManager->getRepository() in C:\wamp\www\idp\vendor\symfony\src\Symfony\Bridge\Doctrine\Security\User\EntityUserProvider.php line 42
at EntityUserProvider->__construct() in C:\wamp\www\idp\app\cache\dev\appDevDebugProjectContainer.php line 2191
at appDevDebugProjectContainer->getSecurity_User_Provider_Concrete_UserDbService() in C:\wamp\www\idp\app\bootstrap.php.cache line 190
at Container->get() in C:\wamp\www\idp\app\cache\dev\appDevDebugProjectContainer.php line 2174
at appDevDebugProjectContainer->getSecurity_User_Provider_Concrete_ChainProviderService() in C:\wamp\www\idp\app\bootstrap.php.cache line 190
at Container->get() in C:\wamp\www\idp\app\cache\dev\appDevDebugProjectContainer.php line 2140
at appDevDebugProjectContainer->getSecurity_Authentication_ManagerService() in C:\wamp\www\idp\app\bootstrap.php.cache line 190
at Container->get() in C:\wamp\www\idp\app\cache\dev\appDevDebugProjectContainer.php line 1304
at appDevDebugProjectContainer->getSecurity_ContextService() in C:\wamp\www\idp\app\bootstrap.php.cache line 190
at Container->get() in C:\wamp\www\idp\app\cache\dev\appDevDebugProjectContainer.php line 1178
at appDevDebugProjectContainer->getProfilerService() in C:\wamp\www\idp\app\bootstrap.php.cache line 190
at Container->get() in C:\wamp\www\idp\app\cache\dev\appDevDebugProjectContainer.php line 1195
at appDevDebugProjectContainer->getProfilerListenerService() in C:\wamp\www\idp\app\bootstrap.php.cache line 190
at Container->get() in C:\wamp\www\idp\app\cache\dev\classes.php line 4779
at ContainerAwareEventDispatcher->lazyLoad() in C:\wamp\www\idp\app\cache\dev\classes.php line 4768
at ContainerAwareEventDispatcher->dispatch() in C:\wamp\www\idp\app\cache\dev\classes.php line 3916
at HttpKernel->handleException() in C:\wamp\www\idp\app\cache\dev\classes.php line 3855
at HttpKernel->handle() in C:\wamp\www\idp\app\cache\dev\classes.php line 4828
at HttpKernel->handle() in C:\wamp\www\idp\app\bootstrap.php.cache line 547
at Kernel->handle() in C:\wamp\www\idp\web\app_dev.php line 20

**------------- Exception/Error End --------------**

让我们描述一下我的申请

  1. 我有三个数据库 DB-A DB-B DB-C ,并在配置中建立三个数据库连接。 yml 文件默认:DB-A, DB_B :DB-B, DB_C :DB-C
  2. 默认连接配置为 default_entity_manager ORM,其他实体经理 DB_B 使用连接DB_B并与MIGPatBundle映射, DB_C 使用连接DB_C并使用MIGPatBundle进行映射。
  3. 我的 UmUsers 实体位于MIGPatBundle中,我们需要在 DB-B 数据库中对其进行验证。
  4. 我详细解释了这些,因为如果我将 default_entity_manager ORM从默认更改为 DB_B ,那么它可以正常工作。
  5. 这是我的文件

    ------------- config.yml开始--------------

    **Doctrine Configuration**
    
    doctrine:
      dbal:
        default_connection:       default
        connections:
            default:
                driver:   "%db_driver_DB-A%"
                host:     "%db_host_DB-A%"
                port:     "%db_port_DB-A%"
                dbname:   "%db_name_DB-A%"
                user:     "%db_user_DB-A%"
                password: "%db_password_DB-A%"
                charset:  UTF8
            DB_B:
                driver:   "%db_driver_DB-B%"
                host:     "%db_host_DB-B%"
                port:     "%db_port_DB-B%"
                dbname:   "%db_name_DB-B%"
                user:     "%db_user_DB-B%"
                password: "%db_password_DB-B%"
                charset:  UTF8
            DB_C:
                driver:   "%db_driver_DB-C%"
                host:     "%db_host_DB-C%"
                port:     "%db_port_DB-C%"
                dbname:   "%db_name_DB-C%"
                user:     "%db_user_DB-C%"
                password: "%db_password_DB-C%"
                charset:  UTF8
    
    orm:
        default_entity_manager:   default
        entity_managers:
            default:
                connection:       default
                mappings:
                    MIGBundle: ~
            DB_B:
                connection:       DB_B
                mappings:
                    MIGPatBundle: ~
            DB_C:
                connection:       DB_C
                mappings:
                    MIGPatBundle: ~
    

    ------------- config.yml结束--------------

    ------------- security.yml开始------------

    security:
    encoders:
        MIG\PatBundle\Entity\UmUsers:
            algorithm: sha512
            encode-as-base64: true
            iterations: 10
    
    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
    
    providers:
        chain_provider:
            providers: [user_db]
        user_db:
            entity: { class: MIG\PatBundle\Entity\UmUsers }
    
    firewalls:
        secured_area:
            pattern:    ^/
            anonymous: ~
            logout:
                target: /
            form_login:
                provider: chain_provider
                check_path:  /security/login_check
                default_target_path: /
                login_path:  /security/login
    
    access_control:
        - { path: ^/account, roles: ROLE_USER }
        - { path: ^/management, roles: ROLE_ADMIN }
        - { path: ^/portfolio, roles: ROLE_USER }
        - { path: ^/portfoliogroup, roles: ROLE_USER }
        - { path: ^/security, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/userpatent, roles: ROLE_USER }
        - { path: ^/_internal, roles: IS_AUTHENTICATED_ANONYMOUSLY, ip: 127.0.0.1 }
    
    access_denied_url: /security/forbidden
    

    ------------- security.yml结束--------------

    -------------用户实体开始--------------

    <?php
    
    namespace MIG\PatBundle\Entity;
    
    use Doctrine\Common\Collections\ArrayCollection;
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    use Symfony\Component\Validator\Constraints as Assert;
    use Symfony\Component\Security\Core\User\UserInterface;
    
    /**
     *MIG\PatBundle\Entity\UmUsers
     *  
     *@ORM\Entity(repositoryClass="MIG\PatBundle\Entity\UserRepository")
     *@ORM\Table(name = "um_users")
     */
    class UmUsers implements UserInterface
    {
    
     /**
      @var string $id
    
      @ORM\Column(name="id", type="string", length=36, nullable=false)
      @ORM\Id
      @ORM\GeneratedValue(strategy="UUID")
     */
    private $id;
    
    /**
     * @ORM\Column(name="user_name", type="string", length=50, nullable=true)
     *
     * @var string $userName
     */
    private $userName;
    
    /**
     * @var string $email
     *
     * @ORM\Column(name="email", type="string", length=100, nullable=false)
     */
    private $email;
    
        /**
     * @ORM\Column(name="password", type="string", length=100, nullable=false)
     *
     * @Assert\MinLength(
     *     limit = 6,
     *     message = "The password must contain at least {{ limit }} characters."
     * )
     * @var string $password
     */
    private $password;
    
    /**
     * @var string $salt
     *
     * @ORM\Column(name="salt", type="string", length=255, nullable=false)
     */
    private $salt;
    
    /**
     * @var string $activationCode
     *
     * @ORM\Column(name="activation_code", type="string", length=255, nullable=false)
     */
    private $activationCode;
    
    /**
     * @var boolean $activated
     *
     * @ORM\Column(name="activated", type="boolean", nullable=true)
     */
    private $activated;
    
    /**
     * @var UmRoles
     *
     * @ORM\ManyToMany(targetEntity="UmRoles", inversedBy="user")
     * @ORM\JoinTable(name="um_usersinroles",
     *   joinColumns={
     *     @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="role_id", referencedColumnName="id")
     *   }
     * )
     */
    private $role;
    
    public function __construct()
    {
        $this->role = new \Doctrine\Common\Collections\ArrayCollection();
        $this->createdAt = new \DateTime();
        $this->lastLoginAt = new \DateTime();
        $this->lastUpdatedDate = new \DateTime();
        $this->lastLoginDate = new \DateTime();
        $this->lastPasswordChangedDate = new \DateTime();
    }
    
    
    /**
     * Get id
     *
     * @return string 
     */
    public function getId()
    {
        return $this->id;
    }
    
    /**
     * Set userName
     *
     * @param string $userName
     */
    public function setUserName($userName)
    {
        $this->userName = $userName;
    }
    
    /**
     * Get userName
     *
     * @return string 
     */
    public function getUserName()
    {
        return $this->userName;
    }
    
    /**
     * Set email
     *
     * @param string $email
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }
    
    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }
    
    /**
     * Set password
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password = $password;
    }
    
    /**
     * Get password
     *
     * @return string 
     */
    public function getPassword()
    {
        return $this->password;
    }
    
    /**
     * Set salt
     *
     * @param string $salt
     */
    public function setSalt($salt)
    {
        $this->salt = $salt;
    }
    
    /**
     * Get salt
     *
     * @return string 
     */
    public function getSalt()
    {
        return $this->salt;
    }
    
    /**
     * Set activationCode
     *
     * @param string $activationCode
     */
    public function setActivationCode($activationCode)
    {
        $this->activationCode = $activationCode;
    }
    
    /**
     * Get activationCode
     *
     * @return string 
     */
    public function getActivationCode()
    {
        return $this->activationCode;
    }
    
    /**
     * Set activated
     *
     * @param boolean $activated
     */
    public function setActivated($activated)
    {
        $this->activated = $activated;
    }
    
    /**
     * Get activated
     *
     * @return boolean 
     */
    public function getActivated()
    {
        return $this->activated;
    }
    
    /**
     * Add role
     *
     * @param MIG\PatBundle\Entity\UmRoles $role
     */
    public function addUmRoles(\MIG\PatBundle\Entity\UmRoles $role)
    {
        $this->role[] = $role;
    }
    
    /**
     * Get role
     *
     * @return Doctrine\Common\Collections\Collection 
     */
    public function getRole()
    {
        return $this->role;
    }
    
    
    
    /**
     * Gets an array of roles.
     *
     * @return array An array of Role objects
     */
    public function getRoles()
    {
        return $this->getRole()->toArray();
    }
    
    /**
     * Erases the user credentials.
     */
    public function eraseCredentials()
    {
    }
    
    
    /**
     * Compares this user to another to determine if they are the same.
     *
     * @param UserInterface $user The user
     * @return booleanean True if equal, false othwerwise.
     */
    public function equals(UserInterface $user)
    {
        return md5($this->getUsername()) == md5($user->getUsername());
    }
    

    }

    -------------用户实体结束--------------

    ------------- UserRepository Entity Start --------------     

    namespace MIG\PatBundle\Entity;
    
    use Symfony\Component\Security\Core\User\UserInterface;
    use Symfony\Component\Security\Core\User\UserProviderInterface;
    use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
    use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
    use Doctrine\ORM\EntityRepository;
    use Doctrine\ORM\NoResultException;
    
    
    class UserRepository extends EntityRepository implements UserProviderInterface
    {
    public function loadUserByUsername($username)
    {
        $q = $this
            ->createQueryBuilder('u')
            ->where('u.userName = :username OR u.email = :email')
            ->setParameter('username', $username)
            ->setParameter('email', $username)
            ->getQuery()
        ;
    
        try {
            // The Query::getSingleResult() method throws an exception
            // if there is no record matching the criteria.
            $user = $q->getSingleResult();
        } catch (NoResultException $e) {
            throw new UsernameNotFoundException(sprintf('Unable to find an active admin MunichInnovationGroup\PatentBundle\Entity\UmUsers object identified by "%s".', $username), null, 0, $e);
        }
    
        return $user;
    }
    
    public function refreshUser(UserInterface $user)
    {
        $class = get_class($user);
        if (!$this->supportsClass($class)) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $class));
        }
    
        return $this->loadUserByUsername($user->getUsername());
    }
    
    public function supportsClass($class)
    {
        return $this->getEntityName() === $class || is_subclass_of($class, $this->getEntityName());
    }
    }
    

    ------------- UserRepository Entity End --------------

    实际上我有完成此任务的截止日期。如果有人能给我解决方案,我会非常感激你。

    此致 Zaif

1 个答案:

答案 0 :(得分:0)

如果您查看vendor / symfony / src / Symfony / Bundle / SecurityBundle / Resources / config / security.xml,您会看到:

<service id="security.user.provider.entity" class="%security.user.provider.entity.class%" abstract="true" public="false"    >
    <argument type="service" id="security.user.entity_manager" />       
</service>
<service id="security.user.entity_manager" alias="doctrine.orm.entity_manager" public="false" />

我认为你需要覆盖security.user.entity_manager,但我不确定如何(可能在security.yml中添加一些行就可以了),并且由于它不公开,我不确定你是否可以。

如果这不起作用,也许您可​​以报告此问题。