2016-01-04 20 views
0

我无法登录到我的受限区域。我正在关注symfony.com上的教程。Symfony3使用UserLoaderInterface扩展UserRepository并使用加密,登录不起作用

我会提供我的security.yml文件。

# To get started with security, check out the documentation: 
# http://symfony.com/doc/current/book/security.html 
security: 
    role_hierarchy: 
     ROLE_ADMIN:  ROLE_USER 
     ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH] 

    encoders: 
     Symfony\Component\Security\Core\User\User: 
      algorithm: bcrypt 
      cost: 12 
     AppBundle\Entity\User: 
      algorithm: bcrypt 
      cost: 12 

    providers: 
     # http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers 
     our_db_provider: 
      entity: 
       class: AppBundle:User 
       # if you're using multiple entity managers 
       # manager_name: customer 

    firewalls: 
     # disables authentication for assets and the profiler, adapt it according to your needs 
     dev: 
      pattern: ^/(_(profiler|wdt)|css|images|js)/ 
      security: false 

     main: 
      pattern: ^/ 
      http_basic: ~ 
      provider: our_db_provider 

      anonymous: ~ 
      # activate different ways to authenticate 

      #http_basic: ~ 
      # http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate 

      # form_login: ~ 
      # http://symfony.com/doc/current/cookbook/security/form_login_setup.html 

      logout: 
       path: /logout 
       target:/

    access_control: 
     # require ROLE_ADMIN for /admin* 
     #- { path: ^/admin, roles: ROLE_ADMIN } 

下一页这里是我的User类

<?php 
// src/AppBundle/Entity/User.php 
namespace AppBundle\Entity; 

use Doctrine\ORM\Mapping as ORM; 
//use Symfony\Component\Security\Core\User\UserInterface; 
use Symfony\Component\Security\Core\User\AdvancedUserInterface; 

/** 
* @ORM\Table(name="app_users") 
* @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository") 
*/ 
class User implements AdvancedUserInterface, \Serializable 
{ 
    /** 
    * @ORM\Column(type="integer") 
    * @ORM\Id 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    private $id; 

    /** 
    * @ORM\Column(type="string", length=25, unique=true) 
    */ 
    private $username; 

    /** 
    * @ORM\Column(type="string", length=64) 
    */ 
    private $password; 

    /** 
    * @ORM\Column(type="string", length=60, unique=true) 
    */ 
    private $email; 

    /** 
    * @ORM\Column(name="is_active", type="boolean") 
    */ 
    private $isActive; 

    public function __construct() 
    { 
     $this->isActive = true; 
     // may not be needed, see section on salt below 
     // $this->salt = md5(uniqid(null, true)); 
    } 

    public function isAccountNonExpired() 
    { 
     return true; 
    } 

    public function isAccountNonLocked() 
    { 
     return true; 
    } 

    public function isCredentialsNonExpired() 
    { 
     return true; 
    } 

    public function isEnabled() 
    { 
     return $this->isActive; 
    } 

    public function getUsername() 
    { 
     return $this->username; 
    } 

    public function getSalt() 
    { 
     // you *may* need a real salt depending on your encoder 
     // see section on salt below 
     return null; 
    } 

    public function getPassword() 
    { 
     return $this->password; 
    } 

    public function getRoles() 
    { 
     return array('ROLE_USER','ROLE_ADMIN'); 
    } 

    public function eraseCredentials() 
    { 
    } 

    /** @see \Serializable::serialize() */ 
    public function serialize() 
    { 
     return serialize(array(
      $this->id, 
      $this->username, 
      $this->password, 
      $this->active 
      // see section on salt below 
      // $this->salt, 
     )); 
    } 

    /** @see \Serializable::unserialize() */ 
    public function unserialize($serialized) 
    { 
     list (
      $this->id, 
      $this->username, 
      $this->password, 
      $this->active 
      // see section on salt below 
      // $this->salt 
     ) = unserialize($serialized); 
    } 

    /** 
    * Get id 
    * 
    * @return integer 
    */ 
    public function getId() 
    { 
     return $this->id; 
    } 

    /** 
    * Set username 
    * 
    * @param string $username 
    * 
    * @return User 
    */ 
    public function setUsername($username) 
    { 
     $this->username = $username; 

     return $this; 
    } 

    /** 
    * Set password 
    * 
    * @param string $password 
    * 
    * @return User 
    */ 
    public function setPassword($password) 
    { 
     $this->password = $password; 

     return $this; 
    } 

    /** 
    * Set email 
    * 
    * @param string $email 
    * 
    * @return User 
    */ 
    public function setEmail($email) 
    { 
     $this->email = $email; 

     return $this; 
    } 

    /** 
    * Get email 
    * 
    * @return string 
    */ 
    public function getEmail() 
    { 
     return $this->email; 
    } 

    /** 
    * Set isActive 
    * 
    * @param boolean $isActive 
    * 
    * @return User 
    */ 
    public function setIsActive($isActive) 
    { 
     $this->isActive = $isActive; 

     return $this; 
    } 

    /** 
    * Get isActive 
    * 
    * @return boolean 
    */ 
    public function getIsActive() 
    { 
     return $this->isActive; 
    } 
} 

,最终用户系统信息库类

<?php 
// src/AppBundle/Repository/UserRepository.php 
namespace AppBundle\Repository\Entity; 

use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface; 
use Symfony\Component\Security\Core\User\UserInterface; 
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; 
use Doctrine\ORM\EntityRepository; 

class UserRepository extends EntityRepository implements UserLoaderInterface 
{ 
    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 (null === $user) { 
      $message = sprintf(
       'Unable to find an active admin AppBundle:User object identified by "%s".', 
       $username 
      ); 
      throw new UsernameNotFoundException($message); 
     } 

     return $user; 
    } 
} 
?> 

我对管理的路线看起来象下面这样:

<?php 

namespace AppBundle\Controller; 

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; 

class DefaultController extends Controller 
{ 
    /** 
    * @Route("/", name="homepage") 
    */ 
    public function indexAction(Request $request) 
    { 
     // replace this example code with whatever you need 
     return $this->render('default/index.html.twig', [ 
      'base_dir' => realpath($this->container->getParameter('kernel.root_dir').'/..'), 
     ]); 
    } 

    /** 
    * @Route("/admin") 
    * @Security("has_role('ROLE_USER') or has_role('ROLE_ADMIN')") 
    */ 
    public function adminAction() 
    { 
     return new Response('<html><body>Admin page!</body></html>'); 
    } 
} 

我试图按照说明在这里登录http://symfony.com/doc/current/cookbook/security/entity_provider.html#using-a-custom-query-to-load-the-user,以便我可以用用户名或电子邮件登录。当我去/管理但是不管我怎么输入电子邮件或用户名到http_basic提示我似乎无法进入。

我猜它可能有一些与编码可能吗?所以在security.yml文件中我使用了两种编码器类型,但它只用1或另一种就不起作用。

记住/管理员具有安全角色的用户或管理员,这样以来我默认的类ROLE_USER的恢复作用应该还是能够得到。

如果有错误日志的地方我米不知道如何找到它。因为我对Symphony还是个新手,所以在这里可以获得帮助。

编辑:

忘记在数据库中提到,目前,我有以下::

1 admin $2y$12$qvLb/T2Xs4aWsFU6D4U2f.gmZi/blKYtspXeqiPLrHPFOPxwMaHY. [email protected] 1 

2 joe $2y$12$M/7nTIEfQ1Ajpr/IhmEVoejskvt0dIb/FfIvT8i9LXdSR95zjT5OS [email protected] 1 

的列是ID,用户名,密码,电子邮件,IS_ACTIVE

加密我手动使用:bin/console security:encode-password,然后放入数据库字段。这工作以前的一些其他记录在我做的测试,但以防万一这是在这里把这个问题。我试着在数据库中放入纯文本,然后输入以登录并且不起作用。

谢谢!

+2

在你的实体配置你的用户仓库是'AppBundle \ Repository \ UserRepository',但是'UserRepository'类中的名字空间是'AppBundle \ Entity'。 – xabbuh

+0

我改变了命名空间,但仍然无法登录。当我不断尝试通过http_basic提示符输入用户名和密码时,提示符就会继续进入无限循环。好,但是,有什么想法? –

+0

要清楚我将命名空间更改为... namespace AppBundle \ Repository \ Entity; –

回答

0

该问题与我的命名空间有关。当使用HTTP_BASIC时,没有简单的方法来查看错误,但UserRepository.php上的名称空间应该是namespace AppBundle\Repository;而不是namespace AppBundle\Repository\Entity;,现在回想起来根本没有意义,因为文件路径甚至不是那么接近。

我确实对我的security.yml文件进行了一些更改,这可能有助于我将它发布到下面。

Security.yml

# To get started with security, check out the documentation: 
# http://symfony.com/doc/current/book/security.html 
security: 
    encoders: 
     Symfony\Component\Security\Core\User\User: 
      algorithm: bcrypt 
      cost: 12 
     AppBundle\Entity\User: 
      algorithm: bcrypt 
      cost: 12 

    role_hierarchy: 
     ROLE_ADMIN:  ROLE_USER 
     ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH] 

    providers: 
     # http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers 
     database: 
       entity: { class: AppBundle:User } 
       #property: username 
       # if you're using multiple entity managers 
       # manager_name: customer 

    firewalls: 
     # disables authentication for assets and the profiler, adapt it according to your needs 
     dev: 
      pattern: ^/(_(profiler|wdt)|css|images|js)/ 
      security: false 
     main: 
      pattern: ^/ 
      anonymous: true 
      # activate different ways to authenticate 

      http_basic: 
       provider: database 
      # http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate 

      # form_login: ~ 
      # http://symfony.com/doc/current/cookbook/security/form_login_setup.html 
      #form_login: 
       #check_path: /login_check 
       #login_path: /login 
       #default_target_path: /home 
       #always_use_default_target_path: true 
       #provider: database 
      logout: 
       path: /logout 
       target:/

    access_control: 
     # require ROLE_ADMIN for /admin* 
     #- { path: ^/admin, roles: ROLE_ADMIN } 
     - { path: ^/admin, roles: ROLE_USER } 

特别是,我给了供应商http_basic所以它知道使用我的数据库为源登录。我之所以有2个编码器是如此,我可以使用控制台命令bin/console security:encode-password,因为该控制台期望该特定类能够工作。我只是给它使用了相同的哈希算法,因此当我使用它为我的用户生成密码时,它同样适用于AppBundle \ Entity \ User类型。当您在没有注册表单的情况下手动创建用户时,控制台命令可以方便地执行bcrypt散列。

user.php的

<?php 
// src/AppBundle/Entity/User.php 
namespace AppBundle\Entity; 

use Doctrine\ORM\Mapping as ORM; 
use Symfony\Component\Validator\Constraints as Assert; 
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; 
use Symfony\Component\Security\Core\User\AdvancedUserInterface; 

/** 
* @ORM\Table(name="app_users") 
* @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository") 
* @UniqueEntity(fields="email", message="Email already taken") 
* @UniqueEntity(fields="username", message="Username already taken") 
*/ 
class User implements AdvancedUserInterface, \Serializable 
{ 
    /** 
    * @ORM\Column(type="integer") 
    * @ORM\Id 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    private $id; 

    /** 
    * @ORM\Column(type="string", length=25, unique=true) 
    * @Assert\NotBlank() 
    */ 
    private $username; 

    /** 
    * The below length depends on the "algorithm" you use for encoding 
    * the password, but this works well with bcrypt 
    * 
    * @ORM\Column(type="string", length=64) 
    */ 
    private $password; 

    /** 
    * @Assert\NotBlank() 
    * @Assert\Length(max = 4096) 
    */ 
    private $plainPassword; 

    /** 
    * @ORM\Column(type="string", length=60, unique=true) 
    * @Assert\NotBlank() 
    * @Assert\Email() 
    */ 
    private $email; 

    /** 
    * @ORM\Column(name="is_active", type="boolean") 
    */ 
    private $isActive; 

    public function __construct() 
    { 
     $this->isActive = true; 
     // may not be needed, see section on salt below 
     // $this->salt = md5(uniqid(null, true)); 
    } 

    public function isAccountNonExpired() 
    { 
     return true; 
    } 

    public function isAccountNonLocked() 
    { 
     return true; 
    } 

    public function isCredentialsNonExpired() 
    { 
     return true; 
    } 

    public function isEnabled() 
    { 
     return $this->isActive; 
    } 

    public function getUsername() 
    { 
     return $this->username; 
    } 

    public function getSalt() 
    { 
     // you *may* need a real salt depending on your encoder 
     // see section on salt below 
     return null; 
    } 

    public function getPassword() 
    { 
     return $this->password; 
    } 

    public function getPlainPassword(){ 
     return $this->plainPassword; 
    } 

    public function getRoles() 
    { 
     return array('ROLE_USER'); 
    } 

    public function eraseCredentials() 
    { 
    } 

    /** @see \Serializable::serialize() */ 
    public function serialize() 
    { 
     return serialize(array(
      $this->id, 
      $this->username, 
      $this->password, 
      $this->isActive 
      // see section on salt below 
      // $this->salt, 
     )); 
    } 

    /** @see \Serializable::unserialize() */ 
    public function unserialize($serialized) 
    { 
     list (
      $this->id, 
      $this->username, 
      $this->password, 
      $this->isActive 
      // see section on salt below 
      // $this->salt 
     ) = unserialize($serialized); 
    } 

    /** 
    * Get id 
    * 
    * @return integer 
    */ 
    public function getId() 
    { 
     return $this->id; 
    } 

    /** 
    * Set username 
    * 
    * @param string $username 
    * 
    * @return User 
    */ 
    public function setUsername($username) 
    { 
     $this->username = $username; 

     return $this; 
    } 

    /** 
    * Set password 
    * 
    * @param string $password 
    * 
    * @return User 
    */ 
    public function setPassword($password) 
    { 
     $this->password = $password; 

     return $this; 
    } 

    /** 
    * Set plainPassword 
    * 
    * @param string $plainPassword 
    * 
    * @return User 
    */ 
    public function setPlainPassword($plainPassword) 
    { 
     $this->plainPassword = $plainPassword; 

     return $this; 
    } 

    /** 
    * Set email 
    * 
    * @param string $email 
    * 
    * @return User 
    */ 
    public function setEmail($email) 
    { 
     $this->email = $email; 

     return $this; 
    } 

    /** 
    * Get email 
    * 
    * @return string 
    */ 
    public function getEmail() 
    { 
     return $this->email; 
    } 

    /** 
    * Set isActive 
    * 
    * @param boolean $isActive 
    * 
    * @return User 
    */ 
    public function setIsActive($isActive) 
    { 
     $this->isActive = $isActive; 

     return $this; 
    } 

    /** 
    * Get isActive 
    * 
    * @return boolean 
    */ 
    public function getIsActive() 
    { 
     return $this->isActive; 
    } 
} 

UserRepository.php

<?php 
// src/AppBundle/Repository/UserRepository.php 
namespace AppBundle\Repository; 

use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface; 
use Symfony\Component\Security\Core\User\UserInterface; 
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; 
use Doctrine\ORM\EntityRepository; 

class UserRepository extends EntityRepository implements UserLoaderInterface 
{ 
    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 (null === $user) { 
      $message = sprintf(
       'Unable to find an active admin AppBundle:User object identified by "%s".', 
       $username 
      ); 
      throw new UsernameNotFoundException($message); 
     } 

     return $user; 
    } 
} 
?> 

DefaultController.php

<?php 

namespace AppBundle\Controller; 

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; 

class DefaultController extends Controller 
{ 
    /** 
    * @Route("/", name="homepage") 
    */ 
    public function indexAction(Request $request) 
    { 
     // replace this example code with whatever you need 
     return $this->render('default/index.html.twig', [ 
      'base_dir' => realpath($this->container->getParameter('kernel.root_dir').'/..'), 
     ]); 
    } 

    /** 
    * @Route("/admin") 
    */ 
    public function adminAction() 
    { 
     return new Response('<html><body>Admin page!</body></html>'); 
    } 
}