Skip to content

Instantly share code, notes, and snippets.

@chalasr
Last active December 14, 2017 09:33
Show Gist options
  • Save chalasr/58bb4ef37ebaf73bdafc to your computer and use it in GitHub Desktop.
Save chalasr/58bb4ef37ebaf73bdafc to your computer and use it in GitHub Desktop.
Generate a token manually in controller - LexikJWTAuthenticationBundle
<?php
namespace App\UserBundle\Controller;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Mangages users authentication in API.
*
* @author Robin Chalas
*/
class SecurityController extends Controller
{
/**
* Register new user account and returns token.
*
* @param Request $request
*/
public function registerUserAccountAction(Request $request)
{
$data = $request->request->all();
$userManager = $this->getUserManager();
return $this->generateToken($this->createUser($data), 201);
}
/**
* Creates new User.
*
* @param array $data
*
* @return User $user
*/
protected function createUser($data)
{
$userManager = $this->getUserManager();
$user = $userManager->createUser();
$user->setUsername($data['name']);
$user->setEmail($data['email']);
$user->setPlainPassword($data['password']);
$user->setEnabled(true);
$userManager->updateUser($user);
return $user;
}
/**
* Generates a JsonWebToken from user.
*/
protected function generateToken($user, $statusCode = 200)
{
// Call the jwt_manager service & create the token
$token = $this->get('lexik_jwt_authentication.jwt_manager')->create($user);
// If you want, add some user informations
$userInformations = array(
'id' => $user->getId(),
'username' => $user->getUsername(),
'email' => $user->getEmail(),
'roles' => $user->getRoles(),
);
// Build your response
$response = array(
'token' => $token,
'user' => $user,
);
// Return the response in JSON format
return new JsonResponse($response, $statusCode);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment