How i can implement refresh token with custom jwt token generation with LexikJWTAuthenticationBundle?

  api-platform.com, jwt, symfony

Currently i create in api platform jwt token with custom symfony controller, provider and encode with JWTEncoderInterface, use authentification come from external api. I have users but not password in my database. How implement refresh token with that system?

security.yml

  providers:
        # used to reload user from session & other features (e.g. switch_user)
        user_provider:
            id: AppSecurityUserProvider
    firewalls:
        dev:
            pattern: ^/_(profiler|wdt)
            security: false
        api:
            pattern: ^/api/
            stateless: true
            anonymous: true
            provider: user_provider
            guard:
                authenticators:
                    - app.authenticator
        main:
            anonymous: true
            stateless: true
            pattern: /authentication_token

My authenticator

 <?php

namespace AppSecurityGuard;


use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;
use LexikBundleJWTAuthenticationBundleEncoderJWTEncoderInterface;

use Throwable;

class Authenticator extends AbstractGuardAuthenticator
{
    private JWTEncoderInterface $jwtEncoder;

    public function __construct(JWTEncoderInterface $jwtEncoder)
    {
        $this->jwtEncoder = $jwtEncoder;
    }

    /**
     * Called on every request to decide if this authenticator should be
     * used for the request. Returning `false` will cause this authenticator
     * to be skipped.
     */
    public function supports(Request $request) : bool
    {
        return $request->headers->has('Authorization Bearer');
    }

    /**
     * Called on every request. Return whatever credentials you want to
     * be passed to getUser() as $credentials.
     */
    public function getCredentials(Request $request) : string
    {
        return $request->headers->get('Authorization Bearer');
    }

    public function getUser($token, UserProviderInterface $userProvider) : UserInterface
    {
        try {
            $user = $this->jwtEncoder->decode($token);
        } catch(Throwable $e) {
            throw new AuthenticationException($e->getMessage());
        }

        return $userProvider->loadUserByUsername($user['email']);
    }

    public function checkCredentials($credentials, UserInterface $user) : bool
    {
        return true;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        // on success, let the request continue
        return null;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception) : JsonResponse
    {
        $failure = [
            'message' => $exception->getMessage()
        ];

        return new JsonResponse($failure, Response::HTTP_UNAUTHORIZED);
    }

    /**
     * Called when authentication is needed, but it's not sent
     */
    public function start(Request $request, AuthenticationException $authException = null) : JsonResponse
    {
        $data = [
            'message' => 'Authentication Required'
        ];

        return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
    }

    public function supportsRememberMe() : bool
    {
        return false;
    }
}

Controller

#[Route('/authentication_token', name: 'security_authentication_token', methods: ['POST'])]
    public function createAuthenticationToken(
        Request $request,
        CreateTokenAuthenticationHandler $createTokenAuthenticationHandler,
        ValidatorInterface $validator
    ): JsonResponse
    {
        $createTokenAuthentication = CreateTokenAuthentication::createFromPayload($request->request->all());
        $errors = $validator->validate($createTokenAuthentication);

        if (count($errors) > 0) {
            foreach ($errors as $error) {
                $message[]=  sprintf("Field %s: %s ", $error->getPropertyPath(), $error->getMessage());
            }
            return new JsonResponse($message, JsonResponse::HTTP_BAD_REQUEST);
        }

        $token = $createTokenAuthenticationHandler->handle($createTokenAuthentication);

        return new JsonResponse(['token' => $token], JsonResponse::HTTP_OK);
    }

Thanks.

Source: Symfony Questions

LEAVE A COMMENT