dongyuan9292 2016-12-14 13:45
浏览 45
已采纳

无法使Symfony身份验证工作

I've been working on a Symfony project and the authentication process is becoming a headache. It seems the configuration files are OK, but when I test, the login page just refreshes an does not authenticate, but it doesn't show any errors either. Someone can help me figure out what I'm missing here?

My security.yml file is like this (I'm using md5 because I'm working on a legacy user base and the %app.locale% I just added because I was thinking maybe the locale prefix in routes was causing this problem):

security:
    access_denied_url: 403
    encoders:
        PsicoBundle\Entity\Usuario:
            algorithm: md5
            encode_as_base64: false
            iterations: 0

    providers:
        in_memory:
            memory: ~

        our_db_provider:
            entity:
                class: PsicoBundle:Entity:Usuario

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            anonymous: ~
            provider: our_db_provider
            form_login:
                login_path: /%app.locales%/login
                check_path: /%app.locales%/login
                default_target_path: /%app.locales%/dashboard
                always_use_default_target_path: true
            logout:
                path: /%app.locales%/logout
                target: /%app.locales%/login

    access_control:
        - { path: ^/%app.locales%/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: /%app.locales%/manage, roles: ROLE_SUPER }
        - { path: /%app.locales%/dashboard, roles: [ROLE_USER, ROLE_SUPER] }

This is how my User Entity looks like:

<?php

namespace PsicoBundle\Entity;

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

use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
//use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Table(name="usuarios")
 * @ORM\Entity(repositoryClass="PsicoBundle\Repository\UsuarioRepository")
 * @ORM\HasLifecycleCallbacks
 *  
 * @ExclusionPolicy("all")
 */

class Usuario implements AdvancedUserInterface, \Serializable {


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

    /**
     * @ORM\Column(type="string")
     * @Assert\NotNull()
     * @Expose
     */
    private $nome;


    /**
     * @ORM\Column(type="string", name="senha")
     * @Expose
     */
    private $password;

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

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

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

    /**
     * @ORM\ManyToOne(targetEntity="Cidade")
     */
    private $cidade;

    /**
     * @ORM\ManyToOne(targetEntity="Idioma")
     */
    private $idioma;

    /**
     * @ORM\Column(type="string", name="email")
     * @Assert\NotNull()
     * @Expose
     */
    private $email;

    /**
     * @ORM\Column(type="boolean")
     * @Expose
     */
    private $ativo;

    /**
     * @ORM\ManyToMany(targetEntity="TipoUsuario", inversedBy="usuarios")
     */
    private $tiposUsuario;


    public function __construct() {
        $this->ativo = true;
        $this->tiposUsuario = new ArrayCollection();
    }

    public function getId() {
        return $this->id;
    }

    public function setId($id) {
        $this->id = $id;
    }

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

    public function setUsername($username) {
        $this->email = $username;
    }

    public function getEmail() {
        return $this->email;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

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

    public function setPassword($password) {
        $this->password = $password;
    }

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


    public function setAtivo($ativo) {
        $this->ativo = $ativo;
    }

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

    public function getPermissao() {
        return $this->tiposUsuario;
    }

    public function getNome() {
        return $this->nome;
    }

    public function setNome($nome) {
        $this->nome = $nome;
    }

    public function serialize() {
        return serialize(array(
            $this->id,
            $this->email,
            $this->password,
            $this->ativo,
            $this->tiposUsuario
        ));
    }

    public function unserialize($serialized) {
        list (
            $this->id,
            $this->email,
            $this->password,
            $this->ativo,
            $this->tiposUsuario
            ) = unserialize($serialized);
    }

    public function getSalt() {
        return null;
    }

    public function eraseCredentials() {

    }

    public function setRoles($tiposUsuario) {
        $this->tiposUsuario = $tiposUsuario;
    }

    /**
     * @return mixed
     */
    public function getEndereco()
    {
        return $this->endereco;
    }

    /**
     * @param mixed $endereco
     */
    public function setEndereco($endereco)
    {
        $this->endereco = $endereco;
    }

    /**
     * @return mixed
     */
    public function getTelefone()
    {
        return $this->telefone;
    }

    /**
     * @param mixed $telefone
     */
    public function setTelefone($telefone)
    {
        $this->telefone = $telefone;
    }

    /**
     * @return mixed
     */
    public function getCelular()
    {
        return $this->celular;
    }

    /**
     * @param mixed $celular
     */
    public function setCelular($celular)
    {
        $this->celular = $celular;
    }


    /**
     * @return mixed
     */
    public function getCidade()
    {
        return $this->cidade;
    }

    /**
     * @param mixed $cidade
     */
    public function setCidade($cidade)
    {
        $this->cidade = $cidade;
    }

    /**
     * @return mixed
     */
    public function getTiposUsuario()
    {
        return $this->tiposUsuario;
    }

    /**
     * @param mixed $tiposUsuario
     */
    public function setTiposUsuario($tiposUsuario)
    {
        $this->tiposUsuario = $tiposUsuario;
    }


    public function isAccountNonExpired()
    {
        return true;
    }

    public function isAccountNonLocked()
    {
        return true;
    }

    public function isCredentialsNonExpired()
    {
        return true;
    }

    /**
     * @return mixed
     */
    public function getIdioma()
    {
        return $this->idioma;
    }


    /**
     * @param mixed $idioma
     */
    public function setIdioma($idioma)
    {
        $this->idioma = $idioma;
    }

}

I also have the Repository class to query the user by its e-mail, tha follows:

 <?php

namespace PsicoBundle\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 UsuarioRepository extends EntityRepository implements UserLoaderInterface
{

    public function loadUserByUsername($username)
    {
        $user = $this->createQueryBuilder()
            ->select('u, g')
            ->from('PsicoBundle:Usuario', 'u')
            ->leftJoin('u.tiposUsuario', 'g')
            ->where('u.email = :email')
            ->setParameter('email', $username)
            ->getQuery()
            ->getOneOrNullResult();

        if (null == $user) {
            $message = sprintf('Usuário com credencial "%s" não encontrado', $username);
            throw new UsernameNotFoundException($message);
        }

        return $user;
    }


}

And my form is like this:

        <form class="m-t" role="form" action="{{ path('login') }}" method="post" id="login-form">
            <div class="form-group">
                <input type="email" class="form-control" placeholder="E-mail" required="" name="_username" value="{{ last_username }}">
            </div>
            <div class="form-group">
                <input type="password" class="form-control" placeholder="{{ 'field.password'|trans }}" required="" name="_password">
            </div>
            <button type="submit" class="btn btn-primary block full-width m-b" name="login">Login</button>

            <p class="text-muted text-center"><small>{{ 'login.calltoaction.text'|trans }}</small></p>
            <a class="btn btn-sm btn-white btn-block" href="{{ path('cadastro_gratis') }}">{{ 'login.testbutton.text'|trans }}</a>
        </form>

The symfony's debug information window show that I'm legged in as anon. And the only thing dev's log shows me is this:

   [2016-12-14 10:59:16] request.INFO: Matched route "{route}". {"route":"_wdt","route_parameters":{"_controller":"web_profiler.controller.profiler:toolbarAction","token":"fe495d","_route":"_wdt"},"request_uri":"http://localhost:8000/_wdt/fe495d","method":"GET"} []
[2016-12-14 11:04:51] request.INFO: Matched route "{route}". {"route":"login","route_parameters":{"_controller":"PsicoBundle\\Controller\\SecurityController::loginAction","_locale":"en","_route":"login"},"request_uri":"http://localhost:8000/en/login","method":"POST"} []
[2016-12-14 11:04:51] security.INFO: Populated the TokenStorage with an anonymous Token. [] []
[2016-12-14 11:04:52] request.INFO: Matched route "{route}". {"route":"_wdt","route_parameters":{"_controller":"web_profiler.controller.profiler:toolbarAction","token":"b4915e","_route":"_wdt"},"request_uri":"http://localhost:8000/_wdt/b4915e","method":"GET"} []

I have an user in my database to test it, and this user has both of the Roles. Can someone help me in this? Thank you guys.

</div>
  • 写回答

2条回答 默认 最新

  • dongsou3041 2016-12-14 21:10
    关注

    Finally figured out what I was doing wrong. In My security.yml I was using the /%app.locales%/ parameter defined in my config.yml as pt_BR|en|es when I should've matched the routes prefix I set in rounting.yml - {_locale) - changed the prefix in my security file routes and authentication went back to normal.

    And also had to take the annotation routes from my controller and insert it in routing.yml

    So my routing now is:

    psico:
        resource: "@PsicoBundle/Controller/"
        type:     annotation
        prefix:   /{_locale}
        requirements:
            _locale: "%app.locales%"
    
    login:
        path: /{_locale}/login
        defaults: { _controller: PsicoBundle:Security:login}
        requirements:
            _locale: "%app.locales%"
    
    logout:
        path: /{_locale}/logout
        defaults: { _controller: PsicoBundle:Security:logout}
        requirements:
            _locale: "%app.locales%"
    

    And my Security is:

    security:
    access_denied_url: 403
    encoders:
        PsicoBundle\Entity\Usuario:
            algorithm: md5
            encode_as_base64: false
            iterations: 0
    
    # http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
    providers:
        our_db_provider:
            entity:
                class: PsicoBundle:Usuario
                property: email
    
    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
    
        main:
            anonymous: ~
            provider: our_db_provider
            form_login:
                login_path: login
                check_path: login
                default_target_path: /dashboard
                always_use_default_target_path: true
                username_parameter: _username
                password_parameter: _password
            logout:
                path: logout
                target: /
    
    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: /manage, roles: ROLE_USER }
        - { path: /dashboard, roles: ROLE_USER }
    

    Thank you, @MohamedBenHenda for helping me trying to solve this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥200 求能开发抖音自动回复卡片的软件
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。