2

So I'm using Lexik JWT bundle (Symfony 2.8) to authenticate over Google and when user is logging in it works well. My Success handler looks like this:

public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
    $user = $token->getUser();
    $jwt  = $this->jwtManager->create($user);
    $response = new JsonResponse();
    $event    = new AuthenticationSuccessEvent(['token' => $jwt], $user, $response);
    $this->dispatcher->dispatch(Events::AUTHENTICATION_SUCCESS, $event);
    $redirectResponse = new RedirectResponse('http://localhost:3000?token='.$event->getData()['token']."&username=".$user->getUsername());
    return $redirectResponse;
}

So I'm redirecting user to some localhost and passing token as "token" get variable and that works well. Later I can pass that token value trough header and I get authenticated.

Problem is - I want to get the same token from my controller. I'm using the similar code:

$jwtManager = $this->get('lexik_jwt_authentication.jwt_manager');

$tokenStorage = $this->get('security.token_storage');
$token = $tokenStorage->getToken();

$user = $token->getUser();
$jwt  = $jwtManager->create($user);
$response = new JsonResponse();
$event    = new AuthenticationSuccessEvent(['token' => $jwt], $user, $response);
$token = $event->getData()['token'];
echo $token;

And I really get some token, but that's not the same one I get from success handler. Tried passing it as header "Autorization" parameter, but it doesn't work. I'm getting 401 error and message:

Unable to verify the given JWT through the given configuration. If the \"lexik_jwt_authentication.encoder\" encryption options have been changed since your last authentication, please renew the token. If the problem persists, verify that the configured keys/passphrase are valid.

What I'm doing wrong here? Why I'm getting different token and how can I get token I'm getting form success handler?

MilanG
  • 6,994
  • 2
  • 35
  • 64

2 Answers2

5

Found the solution. It goes like:

$user = $this->get('security.token_storage')->getToken()->getUser();
$jwtManager = $this->get('lexik_jwt_authentication.jwt_manager');
$token = $jwtManager->create($user);
MilanG
  • 6,994
  • 2
  • 35
  • 64
0

I know this is an old question, but I found a solution that let you use the token anywhere, not just in the controller.

Instead of using TokenInterface, use TokenStorageInterface

public function __construct(TokenStorageInterface $tokenStorage) {
        $this->token = $tokenStorage->getToken();
        $this->user = $this->token->getUser();
}