user26776 user26776 - 3 months ago 49
PHP Question

LexikJWTAuthenticationBundle generate Token

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]);

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

}

Answer

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