Back to blog

DeltaBlue

Refreshing a Json Web Token

x min read

Allowing clients to refresh an existing JWT.Published on 10/21/2018Refreshing a Json Web Token

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.

Let's talk!

Have a question, need advice, or just want to learn more about what we offer? Our team is here to help—whether you're exploring solutions, planning your next move, or already deep into a project.

We'll connect you with the right experts to give you practical, honest input tailored to your situation. No pressure, no hard sell—just a genuine conversation about how we can support your goals.

From technical questions to partnership opportunities, we're all ears. Drop us a line and let's see where we can make a difference.

Contact us