Login to bookmark this video
Buy Access to Course
05.

Create a Shiny JSON Web Token

Share this awesome video!

|

Keep on Learning!

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

Create a new TokenController in the Api directory:

// ... lines 1 - 2
namespace AppBundle\Controller\Api;
use AppBundle\Controller\BaseController;
// ... lines 6 - 9
class TokenController extends BaseController
{
// ... lines 12 - 19
}

Make this extend the same BaseController from our project and let's get to work!

First create a public function newTokenAction(). Add the @Route above and let it autocomplete so that the use statement is added for the annotation. Set the URL to /api/tokens. Heck, let's get crazy and also add @Method: we only want this route to match for POST requests:

// ... lines 1 - 5
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
// ... lines 8 - 9
class TokenController extends BaseController
{
/**
* @Route("/api/tokens")
* @Method("POST")
*/
public function newTokenAction()
{
// ... line 18
}
}

To start, don't get too fancy: just return a new Response from HttpFoundation with TOKEN!:

// ... lines 1 - 7
use Symfony\Component\HttpFoundation\Response;
class TokenController extends BaseController
{
// ... lines 12 - 15
public function newTokenAction()
{
return new Response('TOKEN!');
}
}

Got it! That won't make our test pass, but it is an improvement. Re-run it:

./vendor/bin/phpunit --filter testPOSTCreateToken

Still failing - but now it has the 200 status code.

Checking the Username and Password

Head back to TokenController. Here's the process:

  1. Check that the username and password are correct.
  2. Generate a JSON web token.
  3. Send it back to the client.
  4. High-five everyone at your office. I can't wait to get to that step.

Type-hint a new argument with Request to get the request object:

// ... lines 1 - 8
use Symfony\Component\HttpFoundation\Request;
// ... lines 10 - 12
class TokenController extends BaseController
{
// ... lines 15 - 18
public function newTokenAction(Request $request)
{
// ... lines 21 - 39
}
}

Next, query for a User object with the normal $user = $this->getDoctrine()->getRepository('AppBundle:User') and findOneBy(['username' => '']). Get the HTTP Basic username string with $request->getUser():

// ... lines 1 - 12
class TokenController extends BaseController
{
// ... lines 15 - 18
public function newTokenAction(Request $request)
{
$user = $this->getDoctrine()
->getRepository('AppBundle:User')
->findOneBy(['username' => $request->getUser()]);
// ... lines 24 - 39
}
}

And what if we can't find a user? Throw a $this->createNotFoundException():

// ... lines 1 - 20
$user = $this->getDoctrine()
->getRepository('AppBundle:User')
->findOneBy(['username' => $request->getUser()]);
if (!$user) {
throw $this->createNotFoundException();
}
// ... lines 28 - 41

If you wanted to hide the fact that the username was wrong, you can throw a BadCredentialsException instead - you'll see me do that in a second.

Checking the password is easy: $isValid = $this->get('security.password_encoder') ->isPasswordValid(). Pass it the $user object and the raw HTTP Basic password string: $request->getPassword():

// ... lines 1 - 10
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
class TokenController extends BaseController
{
// ... lines 15 - 18
public function newTokenAction(Request $request)
{
$user = $this->getDoctrine()
->getRepository('AppBundle:User')
->findOneBy(['username' => $request->getUser()]);
if (!$user) {
throw $this->createNotFoundException();
}
$isValid = $this->get('security.password_encoder')
->isPasswordValid($user, $request->getPassword());
if (!$isValid) {
throw new BadCredentialsException();
}
// ... lines 35 - 39
}
}

If this is not valid, throw a new BadCredentialsException. We're going to talk a lot more later about properly handling errors so that we can control the exact JSON returned. But for now, this will at least kick the user out.

Ok, ready to finally generate that JSON web token? Create a $token variable and set it to $this->get('lexik_jwt_authentication.encoder')->encode() and pass that any array of information you want to store in the token. Let's store ['username' => $user->getUsername()] so we know who this token belongs to:

// ... lines 1 - 18
public function newTokenAction(Request $request)
{
$user = $this->getDoctrine()
->getRepository('AppBundle:User')
->findOneBy(['username' => $request->getUser()]);
// ... lines 25 - 35
$token = $this->get('lexik_jwt_authentication.encoder')
->encode([
'username' => $user->getUsername(),
'exp' => time() + 3600 // 1 hour expiration
]);
// ... lines 41 - 42
}

Tip

Don't forget to pass an exp key to the token, otherwise the token will never expire! We forgot to do this in the video!

But you can store anything here, like roles, user information, some poetry - whatever!

And that's it! This is a string, so return a new JsonResponse with a token field set to $token:

// ... lines 1 - 7
use Symfony\Component\HttpFoundation\JsonResponse;
// ... lines 9 - 12
class TokenController extends BaseController
{
// ... lines 15 - 18
public function newTokenAction(Request $request)
{
$user = $this->getDoctrine()
->getRepository('AppBundle:User')
->findOneBy(['username' => $request->getUser()]);
if (!$user) {
throw $this->createNotFoundException();
}
$isValid = $this->get('security.password_encoder')
->isPasswordValid($user, $request->getPassword());
if (!$isValid) {
throw new BadCredentialsException();
}
$token = $this->get('lexik_jwt_authentication.encoder')
->encode([
'username' => $user->getUsername(),
'exp' => time() + 3600 // 1 hour expiration
]);
return new JsonResponse(['token' => $token]);
}

That's it, that's everything. Run the test!

./vendor/bin/phpunit --filter testPOSTCreateToken

It passes! Now, make sure a bad password fails. Duplicate this method:

// ... lines 1 - 6
class TokenControllerTest extends ApiTestCase
{
public function testPOSTCreateToken()
{
$this->createUser('weaverryan', 'I<3Pizza');
$response = $this->client->post('/api/tokens', [
'auth' => ['weaverryan', 'I<3Pizza']
]);
$this->assertEquals(200, $response->getStatusCode());
$this->asserter()->assertResponsePropertyExists(
$response,
'token'
);
}
}

and rename it to testPOSTTokenInvalidCredentials(). But now, we'll lie and pretend my password is IH8Pizza... even though we know that I<3Pizza:

// ... lines 1 - 6
class TokenControllerTest extends ApiTestCase
{
// ... lines 9 - 22
public function testPOSTTokenInvalidCredentials()
{
$this->createUser('weaverryan', 'I<3Pizza');
$response = $this->client->post('/api/tokens', [
'auth' => ['weaverryan', 'IH8Pizza']
]);
$this->assertEquals(401, $response->getStatusCode());
}
}

Check for a 401 status code. Copy the method name and go run that test:

./vendor/bin/phpunit --filter testPOSTTokenInvalidCredentials

It should pass... but it doesn't! Interesting. Look at this: it definitely doesn't return the token... it redirected us to /login. We are getting kicked out of the controller, but this is not how we want our API error responses to work. We'll fix this a bit later.