2

I am using the LexikJWTAuthenticationBundle to generate json token, my problem is that I don't know how I generate a token after verifying that the user is in BD. I am able to help?

My Code.

 public function postLoginAction(Request $request)
    {
        $user = new Utilizador();
        $json = json_decode($request->getContent(), true);
        $user->setUser($json['user']);
        $user->setPass($json['pass']);
        $em = $this->getDoctrine()->getManager();
        $existuser = $em->getRepository('RestBundle:Utilizador')->findOneBy(array(
            'user' => $user->getUser(),
            'pass' => $user->getPass()
        ));
        if($existuser)
    {
        $token =  $this->get('lexik_jwt_authentication.jwt_manager')->create($user);
        return new JsonResponse(['token' => $token]);
    }

    }

My Utilizador Class

 <?php

namespace RestBundle\Entity;

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

/**
 * Utilizador
 *
 * @ORM\Entity
 * @ORM\Table(name="utilizador")
 */
class Utilizador implements UserInterface
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nome", type="string", length=100, nullable=true)
     */
    private $nome;

    /**
     * @var string
     *
     * @ORM\Column(name="user", type="string", length=100, nullable=true)
     */
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(name="pass", type="string", length=100, nullable=true)
     */
    private $pass;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=100, nullable=true)
     */
    private $email;



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

    /**
     * Set nome
     *
     * @param string $nome
     *
     * @return Utilizador
     */
    public function setNome($nome)
    {
        $this->nome = $nome;

        return $this;
    }

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

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

        return $this;
    }

    /**
     * Get user
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

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

        return $this;
    }

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

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

        return $this;
    }

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

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

    public function eraseCredentials()
    {
    }
    public function getSalt()
    {
        return null;
    }
}

Security.yml

security:

    # http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
    providers:
        in_memory:
            memory: ~

    firewalls:

        login:
            pattern:  ^/api/logins
            stateless: true
            anonymous: true

        api:
            pattern:   ^/api
            stateless: true
            lexik_jwt: ~

    access_control:
        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }

Another API Class

<?php
/**
 * Created by PhpStorm.
 * Date: 08/08/16
 * Time: 18:28
 */

namespace RestBundle\Controller;


use RestBundle\Form\StatusType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpKernel\Exception\HttpException;

use RestBundle\Entity\Status;
class StatusController extends FOSRestController
{

    public function getStatusAction()
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('RestBundle:Status')->findAll();

        return $user;
    }

    public function getStatuAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('RestBundle:Status')->find($id);

        if (!$id) {
            throw new HttpException(400, "Invalid id");
        }


        return $user;
    }

    public function postStatusAction(Request $request)
    {
        $user = new Status();
        $json = json_decode($request->getContent(), true);
        $user->setNome($json['nome']);
        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();
        return $user;
    }

}
user26776
  • 131
  • 3
  • 12

1 Answers1

1

Here is how to create a token from a valid Security User:

$token = $this->get('lexik_jwt_authentication.jwt_manager')->create($user);

You can directly try it but I guess it will not work for you as your User entity looks very custom.
To make it works, your User entity must implement the Symfony\Component\Security\Core\User\UserInterface.

For that, instead of manually loading users from your controller via the entity manager, you should really configure the Entity User Provider. See How to load security users from the database

Hope this helps you to go in the right way.

EDIT:

Here is a fully working example of what you have to do for loading users from your database and authenticate them with this bundle:

https://github.com/chalasr/lexik-jwt-authentication-sandbox

chalasr
  • 12,971
  • 4
  • 40
  • 82
  • See this related question too: http://stackoverflow.com/questions/35120309/symfony-2-fosuserbundle-with-rest-login-and-registration/35120807#35120807 – chalasr Aug 23 '16 at 12:16
  • I got that i returns a token now when I make a call to the API with the token she returns this `{ "code": 401, "message": "Username \"master\" does not exist."}` – user26776 Aug 23 '16 at 14:04
  • It means that there is no user with property `username` equal to `master`. Are you using `username` as property name (you can configure another on the bundle)? Otherwise, is your user correctly registered in db? – chalasr Aug 23 '16 at 14:13
  • I added a class Utilizador to the post , Yes the user exists in BD – user26776 Aug 23 '16 at 14:34
  • Change the name of the property `$user` to `$username` in `Utilizador` (adapt the property name in getUsername() and setUser() too) you should be ok. Keep me informed. BTW `setUser()` should be called `setUsername()` by convention. – chalasr Aug 23 '16 at 14:37
  • I changed but it still does not work. :( [http://i1069.photobucket.com/albums/u479/thepeterpah/Captura%20de%20ecra%202016-08-23%20as%2016.06.27_zpsxhw0b5eu.png] – user26776 Aug 23 '16 at 15:13
  • Please change the column name according to your property name, i.e change from `* @ORM\Column(name="user", ...)` to `* @ORM\Column(name="username", ...)` – chalasr Aug 23 '16 at 15:40
  • Updated your database schema since you changed the column name ? – chalasr Aug 23 '16 at 15:52
  • Yes of course . [ http://i1069.photobucket.com/albums/u479/thepeterpah/Captura%20de%20ecra%202016-08-23%20as%2017.02.17_zpsw1rkdf1n.png] – user26776 Aug 23 '16 at 16:01
  • I do not know what to do more walk around this 2 weeks and not working :S – user26776 Aug 23 '16 at 16:59
  • Can you update your securiy configuration and your `Utilizador` entity? If nothing comes to me we'll debug it together in a chat if you're ok – chalasr Aug 23 '16 at 17:16
  • Please take example from the sample I given you. You do not need to nor create the token manually neither check if your user is correct from your controller. Just configure the built-in entity provider using the link I given you, configure the bundle as documented,then just profit! Rewriting stuff that already exist on top of the framework will never help you, this is the whole point of using a framework like Symfony. I hope you take the time to discover and appreciate all these built-in stuff that make it powerfull for Rapid application development as well as other approaches like DDD. – chalasr Aug 23 '16 at 18:05
  • Thank you , I don't understand how the symfony knows that when i call the /login_check he has to go to bd check if there is a user , for example and if i want to make other operations when after checking the login how do i do this? – user26776 Aug 24 '16 at 08:40
  • It is all handled by configuration, the provider you confugured checks that your user exists by using the Doctrine repository of your entity with findBy(), then the lexik_jwt option set in your secured firewall make the JWTListener enabled, which uses your user provider to make the user check too! That's the powerful Symfony security component, look at it to see more. Glad to helped you! – chalasr Aug 24 '16 at 08:47
  • Imagine that i wanted to do other operations after checking if the login is there how can I do this? Do you have any examples in your github? – user26776 Aug 24 '16 at 09:17
  • For example in your code I would like to check if the user is active before return the token as I can do this – user26776 Aug 24 '16 at 09:42
  • Take a quick look at the LexikJWTAuthenticationBundle documentation https://github.com/lexik/LexikJWTAuthenticationBundle/blob/master/Resources/doc/2-data-customization.md, it gives you all in hand to perform custom validation by creating an EventListener listening on the JWTDecodedEvent. See https://github.com/lexik/LexikJWTAuthenticationBundle/issues/193 for a concrete example – chalasr Aug 24 '16 at 17:14
  • I changed my code on GitHub is working , but if you can take a look and tell me what I can improve was grateful https://github.com/masterloge/MySmfonyProject – user26776 Aug 25 '16 at 13:17
  • No problem, I'll take a look as soon as possible today – chalasr Aug 25 '16 at 14:07