Youssef SABIH
Youssef SABIH

Reputation: 659

How to use the authenticated user's jwt token in an http request to an external service in Symfony 4.4?

I'm working with a PHP/Symfony 4.4 Backend api which authenticates users via jwt tokens created by an external identity service. lexik/jwt-authentication-bundle is used to validate tokens. I need to send an http request to an external service route with the user's jwt token to get some necessary data because the route returns the data depending the sub field in the jwt token. I tried getting the raw jwt token using TokenStorageInterface (tokenStorage->getToken()->$rawToken) but the property is protected.

Here is a preview of the object returned by tokenStorage->getToken()->$rawToken:

object(Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\JWTUserToken)[638] protected 'rawToken' => string ''... (length=1476) protected 'providerKey' => string 'api' (length=3) private 'user' (Symfony\Component\Security\Core\Authentication\Token\AbstractToken)...

Upvotes: 1

Views: 777

Answers (1)

Pickle
Pickle

Reputation: 11

You can get the encoded token string from

\Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\TokenExtractorInterface

Watch in your lexik_jwt_authentication.yaml, if you have token extractors specified. Here is a configuration for 2 token extractors. One to extract from authorization-header und another to extract from cookie:

lexik_jwt_authentication:
  ...
  token_extractors:
    authorization_header:
      enabled: true
      prefix: Bearer
      name: Authorization
    cookie:
      enabled: true
      name: 'TOKEN_COOKIE_NAME'

If so, you can use the service

lexik_jwt_authentication.extractor.chain_extractor

from your service-container to get the raw token.

BUT! this service is private, so you have either to inject it via services.yaml into your object or, if using autowiring, write a method within your controller class or the like and mark it as required:

/**
 * @required
 */
public function setTokenExtractor(TokenExtractorInterface $tokenExtractor)
{
    $this->tokenExtractor = $tokenExtractor;
}

You won't retrieve it by containers get() method!

Finally call the extract method on TokenExtractorInterface

$rawToken = $this->tokenExtractor->extract(<instance of current request>);

Upvotes: 1

Related Questions