1

情况:我正在开发从本机 iOS 应用程序访问的 Web 服务,我不需要使用 Web 表单,只需要标准的 NSURLRequests 并准备好使用 didReceiveAuthenticationChallenge,因此如果有一天有 Web/Android 版本,我可以获得灵活性。

它使用教义。现在我不想使用 FOSUserBundle,因为我只需要电子邮件和密码,而不是用户名。现在我可以注册新用户并将他们分配给一个组('ROLE_USER',在 db 中手动创建但通过关系分配),所以实体似乎工作正常。

问题:访问 my_site/login 并出现 http auth web 框。但是当我输入用户名(电子邮件帐户)和密码时,该框再次出现空白,检查它们是否正常。

代码:security.yml

jms_security_extra:
secure_all_services: false
expressions: true

security:
    encoders:
        Satori\WarnMeBundle\Entity\User:
            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:
           main:
               entity: { class: SatoriWarnMeBundle:User }

    firewalls:                  
        login:
            pattern:  ^/login$    
            http_basic:
            realm: "Warn Me App"

    access_control:        
        - { path: /login, roles: IS_AUTHENTICATED_ANONYMOUSLY }        
        - { path: /register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: /.*, roles: IS_AUTHENTICATED_ANONYMOUSLY }

安全控制器

 namespace Satori\WarnMeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\JsonResponse;
use Satori\WarnMeBundle\Entity\User;

class SecurityController extends Controller {

public function loginAction() {
    $request = $this->getRequest();
    $session = $request->getSession();
    $errors = array();        
    // get the login error if there is one
    if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
        $authError = $request->attributes->get(
                SecurityContext::AUTHENTICATION_ERROR);
        if (null != $authError) {
            $errors['Authentication Error Key'] = $authError->getMessageKey();
            $errors['Authentication Error Data'] = $authError->getMessageData();
        }
    } else {
        $authError = $session->get(SecurityContext::AUTHENTICATION_ERROR);
        $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        if (null != $authError) {
            $errors['Authentication Error Key'] = $authError->getMessageKey();
            $errors['Authentication Error Data'] = $authError->getMessageData();
        }
    }

    if ($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
        $errors[] = 'Fully authenticated';
    }

    return new JsonResponse(array('name' => $session->get(SecurityContext::LAST_USERNAME),
        'error' => $errors));
}

public function validateUser($user) {
    //Validar campos
    $validator = $this->get('validator');
    $errors = $validator->validate($user);
    if (count($errors) > 0) {
        return $errors;
    }
    return;
}

public function encodePassword($user, $password) {
    $factory = $this->get('security.encoder_factory');
    $encoder = $factory->getEncoder($user);
    $password = $encoder->encodePassword($password, $user->getSalt());
    return $password;
}

public function registerAction() {
    $this->getEmailAndPassword();
    $errors = array();
    //Mirar si existe        
    $exists = $this->getDoctrine()
            ->getRepository('SatoriWarnMeBundle:User')
            ->findByEmail($this->email);
    if (!$exists) {
        //No existe o vacío, validar
        $user = new User();
        $user->setEmail($this->email);
        //Codificar password
        $user->setPassword($this->encodePassword($user, $this->password));
        $groupsRepository = $this->getDoctrine()->getRepository('SatoriWarnMeBundle:Group');
        $group = $groupsRepository->findOneByName('ROLE_USER');
        if (!$group) {
            $errors[] = "No hay grupo";
        } else {
            $user->addGroup($group);
        }
        $validFields = $this->validateUser($user);
        if ((count($validFields)) > 0) {
            foreach ($validFields as $value) {
                $val = $value->getMessage();
                $errors[] = $val;
            }
        } else {
            try {
                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $em->persist($group);
                $em->flush();
            } catch (Exception $e) {
                if ($e) {
                    $errors[] = $e->getMessage();
                }
            }

            return new JsonResponse(array('message' => 'Created'), 201);
        }
    } else {
        $errors[] = 'Ya existe';
    }
    return new JsonResponse(array('errors' => $errors));
}

private function getEmailAndPassword() {
    $request = $this->getRequest();
    $content = $request->getContent();
    $params = NULL;
    if (!empty($content)) {
        $params = json_decode($content, true);
    }
    $this->email = $params['email'];
    $this->password = $params['password'];
}
}

?>

用户

namespace Satori\WarnMeBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Satori\WarnMeBundle\Entity\User
 *
 * @ORM\Table(name="Satori_users")
 * @ORM\Entity(repositoryClass="Satori\WarnMeBundle\Entity\UserRepository")
 */
class User implements AdvancedUserInterface, \Serializable {

/**
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")    
 */
private $id;

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

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

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

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

public function __construct() {
    $this->isActive = true;
    $this->salt = md5(uniqid(null, true));
    $this->groups = new ArrayCollection();
}

/**
 * @inheritDoc
 */
public function getUsername() {
    return $this->email;
}

/**
 * @inheritDoc
 */
public function getSalt() {
    return $this->salt;
}

/**
 * @inheritDoc
 */
public function getPassword() {
    return $this->password;
}

/**
 * @inheritDoc
 */
public function eraseCredentials() {

}

/**
 * @inheritDoc
 */
public function isEqualTo(UserInterface $user) {
    return $this->id === $user->getId();
}

/**
 * @see \Serializable::serialize()
 */
public function serialize() {
    return serialize(array(
        $this->id,
    ));
}

/**
 * @see \Serializable::unserialize()
 */
public function unserialize($serialized) {
    list (
            $this->id,
            ) = unserialize($serialized);
}

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

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

    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;
}

public function isAccountNonExpired() {
    return true;
}

public function isAccountNonLocked() {
    return true;
}

public function isCredentialsNonExpired() {
    return true;
}

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

/**
 * @ORM\ManyToMany(targetEntity="Group", inversedBy="users")
 *
 */
private $groups;

public function getRoles() {
    return $this->groups->toArray();
}

/**
 * Add groups
 *
 * @param \Satori\WarnMeBundle\Entity\Group $groups
 * @return User
 */
public function addGroup(\Satori\WarnMeBundle\Entity\Group $groups) {
    $this->groups[] = $groups;

    return $this;
}

/**
 * Remove groups
 *
 * @param \Satori\WarnMeBundle\Entity\Group $groups
 */
public function removeGroup(\Satori\WarnMeBundle\Entity\Group $groups) {
    $this->groups->removeElement($groups);
}

/**
 * Get groups
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getGroups() {
    return $this->groups;
}

}

用户存储库

/**
 * Satori\WarnMeBundle\Entity\User
 *
 * @ORM\Table(name="Satori_users")
 * @ORM\Entity(repositoryClass="Satori\WarnMeBundle\Entity\UserRepository")
 */
 class User implements AdvancedUserInterface, \Serializable {

/**
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")    
 */
private $id;

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

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

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

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

public function __construct() {
    $this->isActive = true;
    $this->salt = md5(uniqid(null, true));
    $this->groups = new ArrayCollection();
}

/**
 * @inheritDoc
 */
public function getUsername() {
    return $this->email;
}

/**
 * @inheritDoc
 */
public function getSalt() {
    return $this->salt;
}

/**
 * @inheritDoc
 */
public function getPassword() {
    return $this->password;
}

/**
 * @inheritDoc
 */
public function eraseCredentials() {

}

/**
 * @inheritDoc
 */
public function isEqualTo(UserInterface $user) {
    return $this->id === $user->getId();
}

/**
 * @see \Serializable::serialize()
 */
public function serialize() {
    return serialize(array(
        $this->id,
    ));
}

/**
 * @see \Serializable::unserialize()
 */
public function unserialize($serialized) {
    list (
            $this->id,
            ) = unserialize($serialized);
}

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

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

    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;
}

public function isAccountNonExpired() {
    return true;
}

public function isAccountNonLocked() {
    return true;
}

public function isCredentialsNonExpired() {
    return true;
}

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

/**
 * @ORM\ManyToMany(targetEntity="Group", inversedBy="users")
 *
 */
private $groups;

public function getRoles() {
    return $this->groups->toArray();
}

/**
 * Add groups
 *
 * @param \Satori\WarnMeBundle\Entity\Group $groups
 * @return User
 */
public function addGroup(\Satori\WarnMeBundle\Entity\Group $groups) {
    $this->groups[] = $groups;

    return $this;
}

/**
 * Remove groups
 *
 * @param \Satori\WarnMeBundle\Entity\Group $groups
 */
public function removeGroup(\Satori\WarnMeBundle\Entity\Group $groups) {
    $this->groups->removeElement($groups);
}

/**
 * Get groups
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getGroups() {
    return $this->groups;
}

}    

组/类 组扩展角色 { /* * @ORM\Column(name="id", type="integer") * @ORM\Id() * @ORM\GeneratedValue(strategy="AUTO") */ private $ ID;

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

/**
 * @ORM\Column(name="role", type="string", length=20, unique=true)
 */
private $role;

/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="groups")
 */
private $users;

public function __construct()
{
    $this->users = new ArrayCollection();
}


/**
 * @see RoleInterface
 */
public function getRole()
{
    return $this->role;
}

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

/**
 * Set name
 *
 * @param string $name
 * @return Group
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

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

/**
 * Set role
 *
 * @param string $role
 * @return Group
 */
public function setRole($role)
{
    $this->role = $role;

    return $this;
}

/**
 * Add users
 *
 * @param \Satori\WarnMeBundle\Entity\User $users
 * @return Group
 */
public function addUser(\Satori\WarnMeBundle\Entity\User $users)
{
    $this->users[] = $users;

    return $this;
}

/**
 * Remove users
 *
 * @param \Satori\WarnMeBundle\Entity\User $users
 */
public function removeUser(\Satori\WarnMeBundle\Entity\User $users)
{
    $this->users->removeElement($users);
}

/**
 * Get users
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getUsers()
{
    return $this->users;
}
}

杂项:现在只是测试 /login 我正在使用 Advanced Rest Client 进行内部测试,所以我认为这不是客户端问题。如果您需要任何其他代码,请索取。

非常感谢!!!

4

0 回答 0