Blogpost

2 minute read

Refreshing a Json Web Token

Allowing clients to refresh an existing JWT.

In the previous post we have setup an authentication API.

As JWT will expire, it would be very useful to allow clients to refresh that token, so they don’t have to re-authenticate users ( meaning asking for credentials again ).

We will do this by adding a token refresh route:

user_refresh_token:
    path: /token-refresh
    controller: App\Controller\AuthenticationController:refreshTokenAction

and allow access to that route to all users with a valid JWT Token, by altering security.yaml.

secured_users:
    pattern: ^/token-refresh$
    provider: jwt_user_provider
    stateless: true
    guard:
        authenticators:
            - lexik_jwt_authentication.jwt_token_authenticator

The actual refresh token logic goes in the AuthenticationController:

<?php

namespace App\Controller;

// Insert missing use statements.

class AuthenticationController extends Controller
{
    /**
     * Get a new JWT Token while current JWT token is still active.
     *
     * @param Request $request
     * @return JWTAuthenticationSuccessResponse
     */
    public function refreshTokenAction(Request $request)
    {
        $user = $this->getUser();
        $jwtToken = $this->get('lexik_jwt_authentication.jwt_manager')->create($user);
        $response = new JWTAuthenticationSuccessResponse($jwtToken);

        $event = new AuthenticationSuccessEvent(['token' => $jwtToken], $user, $response);
        $dispatcher = $this->get('event_dispatcher');
        $dispatcher->dispatch(Events::AUTHENTICATION_SUCCESS, $event);
        $response->setData($event->getData());

        return $response;
    }
}

And that’s it.

Security is handled by JWT. When a client ( or user ) is not fully authenticated, he will not be able to get a new token, but when an authenticated client calls /token-refresh it will get a new token. Simple as that.

This is a very small feature, but one that is of utmost importance, that allows you to set the lifetime of your tokens lower, thus increasing platform security.

Now it’s time to see how clients can validate the received tokens.

Want to find out what we can do for you?