Score:0

How to get current user jwt token?

ni flag

In a custom module, I need to get the jwt token (access_token) related to the current user. Following this issue I've tried to get it, but without success, because get_jwt_key() and jwt_token_params() are not defined and I can't find where they are defined:

use \Firebase\JWT\JWT;
...    
public function getAccessToken() {
  $uid = \Drupal::currentUser()->id();
  // Add JWT access_token
  $key = get_jwt_key(); //key for generate jwt token
  $token = jwt_token_params($uid); // parameters to be added in token.
  $access_token = JWT::encode($token, $key);
  return $access_token;
}

I've tried only with:

$access_token = $this->jwtAuth->generateToken();

But I haven't found how to initialize $jwtAuth service to generate the token. Any suggestion?

Score:2
us flag

The code shown on comment #2 in Get the token bearer with the JWT module after log in rest method is the code for an event subscriber class. What that comment doesn't show is the definition of the event subscriber service.

As described in Subscribe to and dispatch events / Drupal 8 Events, the .services.yml file should contain lines similar to the following ones. (Replace YOURMODULE with the module machine name, and YOURCLASS with the class name.)

services:
  YOURMODULE_YOURCLASS:
    class: '\Drupal\YOURMODULE\Listener\YOURCLASS'
    tags:
      - { name: 'event_subscriber' }
    arguments:
      - '@path.current'
      - '@jwt.authentication.jwt'

Contrary to what the comment says, the file containing the \Drupal\YOURMODULE\Listener\YOURCLASS class isn't the src/Listener/yourfile.php file, but the src/Listener/YOURCLASS.php file contained in the module directory.

As side notes:

  • As described in Events, the file containing an event subscriber class isn't required to be in a specific directory. Drupal core modules normally put those files in the EventSubscriber directory.

  • The JSON Web Token Authentication (JWT) module doesn't define neither get_jwt_key() nor jwt_token_params(). The comment doesn't show the code for those functions, but they need to be implemented from the module. (In that case, their names should be prefixed by the module machine name.) -The YOURCLASS class shown in that comment initializes $this->jwtAuth in its constructor, but onHttpLoginResponse() doesn't even use it.

    /**
     * Add JWT access token to user login API response
     */
    public function onHttpLoginResponse(FilterResponseEvent $event) {
      // Halt if not user login request
      if ($this->currentPath->getPath() !== '/user/login') {
        return;
      }
      // Get response
      $response = $event->getResponse();
      // Ensure not error response
      if ($response->getStatusCode() !== 200) {
        return;
      }
      // Get request
      $request = $event->getRequest();
      // Just handle JSON format for now
      if ($request->query->get('_format') !== 'json') {
        return;
      }
      // Decode and add JWT token
      if ($content = $response->getContent()) {
        if ($decoded = Json::decode($content)) {
          $uid = $decoded['current_user']['uid'];
          // Add JWT access_token
          $key = get_jwt_key(); //key for generate jwt token
          $token = jwt_token_params($uid); // parameters to be added in token.
          $access_token = JWT::encode($token, $key);
          $decoded['jwt_access_token'] = $access_token;
          // Set new response JSON
          $response->setContent(Json::encode($decoded));
          $event->setResponse($response);
        }
      }
    } 
    

    Clearly, the code shown in that comment is incomplete.

ni flag
Thanks for your help. After reading and some test I did it with this: $jwt = \Drupal::service('jwt.authentication.jwt'); $access_token = $jwt->generateToken();
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.