Click here to Skip to main content
15,894,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

This is a Question for who are Symfony2 developer.

I am trying to study security feature provided with Symfony2.

I tried to get help from http://symfony.com/doc/current/cookbook/security/entity_provider.html[^]

But every time I found Bad Credential. I did not use any encryption algorithm ( i mention encoder plaintext).

Only change in my case is , instead of username field i am using email of user for verification.
Following are my files.
PHP
<?php
// src\Acme\DemoBundle\Controller\SecurityController.php

namespace Acme\DemoBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

/**
 * @Route("/demo/secured")
 */
class SecuredController extends Controller
{
    /**
     * @Route("/login", name="_demo_login")
     * @Template()
     */
    public function loginAction(Request $request)
    {
        $variable  = 0;
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $variable  = 1;
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $variable  = 2;
            $error = $request->getSession()->get(SecurityContext::AUTHENTICATION_ERROR);
            var_dump($error);
        }
        var_dump($variable);
        return array(
            'last_username' => $request->getSession()->get(SecurityContext::LAST_USERNAME),
            'error'         => $error,
        );
    }

    /**
     * @Route("/login_check", name="_security_check")
     */
    public function securityCheckAction()
    {
        // The security layer will intercept this request
    }

    /**
     * @Route("/logout", name="_demo_logout")
     */
    public function logoutAction()
    {
        // The security layer will intercept this request
    }

    /**
     * @Route("/hello", defaults={"name"="World"}),
     * @Route("/hello/{name}", name="_demo_secured_hello")
     * @Template()
     */
    public function helloAction($name)
    {
        return array('name' => $name);
    }

    /**
     * @Route("/hello/admin/{name}", name="_demo_secured_hello_admin")
     * @Template()
     */
    public function helloadminAction($name)
    {
        return array('name' => $name);
    }
}


My entities are as per below.
PHP
<?php
namespace Acme\DemoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 * @ORM\HasLifecycleCallbacks()
 */

class Users implements UserInterface{
    
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id_user;
    /**
     * @ORM\Column(type="string", length=50)
     */
    private $first_name;
    /**
     * @ORM\Column(type="string", length=50)
     */
    private $last_name;
    /**
     * @ORM\Column(type="string", length=100)
     */
    private $email;
    /**
     * @ORM\Column(type="string", length=100)
     */
    private $password;
    /**
     * @ORM\Column(type="string", length=100)
     */
    private $salt;
    /**
     * @ORM\Column(type="boolean")
     */
    private $password_change;
    /**
     * @ORM\Column(type="string", length=20)
     */
    private $phone_no;
    /**
     * @ORM\Column(type="string", length=400)
     */
    private $address;
    /**
     * @ORM\Column(type="datetime")
     */
    private $created_at;
    /**
     * @ORM\Column(type="datetime")
     */
    private $updated_at;
    
    /**
     * @ORM\Column(type="boolean")
     */
    private $is_active;

    /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
     * @ORM\JoinTable(name="users_role",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id_user")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id_role")}
     *      )
     *
     */
    private $roles;

    public function __construct()
    {
        $this->roles = new ArrayCollection();
        $this->salt = md5(uniqid(null,true));
    }
    
    /**
     * Get id_user
     *
     * @return integer 
     */
    public function getIdUser()
    {
        return $this->id_user;
    }

    /**
     * Set first_name
     *
     * @param string $firstName
     * @return Users
     */
    public function setFirstName($firstName)
    {
        $this->first_name = $firstName;
    
        return $this;
    }

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

    /**
     * Set last_name
     *
     * @param string $lastName
     * @return Users
     */
    public function setLastName($lastName)
    {
        $this->last_name = $lastName;
    
        return $this;
    }

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

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

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

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

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

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

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

    /**
     * Set password_change
     *
     * @param boolean $passwordChange
     * @return Users
     */
    public function setPasswordChange($passwordChange)
    {
        $this->password_change = $passwordChange;
    
        return $this;
    }

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

    /**
     * Set phone_no
     *
     * @param string $phoneNo
     * @return Users
     */
    public function setPhoneNo($phoneNo)
    {
        $this->phone_no = $phoneNo;
    
        return $this;
    }

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

    /**
     * Set address
     *
     * @param string $address
     * @return Users
     */
    public function setAddress($address)
    {
        $this->address = $address;
    
        return $this;
    }

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

    /**
     * Set created_at
     *
     * @param \DateTime $createdAt
     * @return Users
     */
    public function setCreatedAt($createdAt)
    {
        $this->created_at = $createdAt;
    
        return $this;
    }

    /**
     * Get created_at
     *
     * @return \DateTime 
     */
    public function getCreatedAt()
    {
        return $this->created_at;
    }

    /**
     * Set updated_at
     *
     * @param \DateTime $updatedAt
     * @return Users
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updated_at = $updatedAt;
    
        return $this;
    }

    /**
     * Get updated_at
     *
     * @return \DateTime 
     */
    public function getUpdatedAt()
    {
        return $this->updated_at;
    }

    /**
     * Set active
     *
     * @param boolean $active
     * @return Users
     */
    public function setActive($active)
    {
        $this->active = $active;
    
        return $this;
    }

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

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

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

    public function eraseCredentials() {
        
    }

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

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

    public function isAccountNonExpired() {
        return true;
    }

    public function isAccountNonLocked() {
        return true;
    }

    public function isCredentialsNonExpired() {
        return true;
    }

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

    /**
     * Add roles
     *
     * @param \OxindDemo\AdminBundle\Entity\Role $roles
     * @return Users
     */
    public function addRole(\OxindDemo\AdminBundle\Entity\Role $roles)
    {
        $this->roles->add( $roles );
    
        return $this;
    }

    /**
     * Remove roles
     *
     * @param \OxindDemo\AdminBundle\Entity\Role $roles
     */
    public function removeRole(\OxindDemo\AdminBundle\Entity\Role $roles)
    {
        $this->roles->removeElement($roles);
    }
}


Role Entity

PHP
<?php

namespace Acme\DemoBundle\Entity;

use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * @ORM\Entity
 * @ORM\Table(name="role")
 */
class Role implements RoleInterface{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id_role;
    
    /**
     * @ORM\Column(type="string",length=50,unique=true)
     */
    private $role_name;

  
    private $users;

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }
    
    /**
     * Get id_role
     *
     * @return integer 
     */
    public function getIdRole()
    {
        return $this->id_role;
    }

    /**
     * Set role_name
     *
     * @param string $roleName
     * @return UsersRole
     */
    public function setRoleName($roleName)
    {
        $this->role_name = $roleName;
    
        return $this;
    }

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

    public function getRole() {
        return $this->role_name;
    }

    /**
     * Add users
     *
     * @param \OxindDemo\AdminBundle\Entity\Users $users
     * @return Role
     */
    public function addUser(\OxindDemo\AdminBundle\Entity\Users $users)
    {
        $this->users[] = $users;
    
        return $this;
    }

    /**
     * Remove users
     *
     * @param \OxindDemo\AdminBundle\Entity\Users $users
     */
    public function removeUser(\OxindDemo\AdminBundle\Entity\Users $users)
    {
        $this->users->removeElement($users);
    }

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


My Securtiy.yml as below.

VB
security:
    encoders:
        Symfony\Component\Security\Core\User\User: plaintext
        Acme\DemoBundle\Entity\Users: plaintext
    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

    providers:
        in_memory:
            memory:
                users:
                    user:  { password: userpass, roles: [ 'ROLE_USER' ] }
                    admin: { password: adminpass, roles: [ 'ROLE_ADMIN' ] }
        main:
          entity:
            class: Acme\DemoBundle\Entity\Users
            property: email

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

        login:
            pattern:  ^/demo/secured/login$
            security: false

        secured_area:
            pattern:    ^/demo/secured/
            form_login:
                check_path: _security_check
                login_path: _demo_login
            logout:
                path:   _demo_logout
                target: _demo
            #anonymous: ~
            #http_basic:
            #    realm: "Secured Demo Area"

    access_control:
        - { path: ^/demo/secured/hello/admin/, roles: ROLE_ADMIN }
        #- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }



I have created a user with email myuser@mail.com and password: mypass and having Role Entry ROLE_ADMIN and a mapping of myuser with ROLE_ADMIN role in user_role table.

Every time i tried to login with myuser@mail.com/mypass. It says Bad credentials. I can't get why it can't verify my user from database?

Sorry For My Bad English.
I spent almost 2 days google it. tried 8 times to follow different tutorials but can't get my problem solved.

Thanks
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900