You are here

public function UserAuthTest::testAuth in JSON Web Token Authentication (JWT) 8

Verify the authentication for a user.

File

tests/src/Kernel/UserAuthTest.php, line 46

Class

UserAuthTest
Tests JWT config schema.

Namespace

Drupal\Tests\jwt\Kernel

Code

public function testAuth() {
  $account = $this
    ->createUser([
    'access content',
  ]);
  $this
    ->setCurrentUser($account);

  /** @var \Drupal\jwt\Authentication\Provider\JwtAuth $auth */
  $auth = $this->container
    ->get('jwt.authentication.jwt');
  $token = $auth
    ->generateToken();

  /** @var \Drupal\jwt\Transcoder\JwtTranscoderInterface $transcoder */
  $transcoder = $this->container
    ->get('jwt.transcoder');
  $decoded_jwt = $transcoder
    ->decode($token);
  $this
    ->assertEqual($account
    ->id(), $decoded_jwt
    ->getClaim([
    'drupal',
    'uid',
  ]));

  /** @var \Drupal\Core\Authentication\AuthenticationProviderInterface $auth_service */
  $auth_service = $this->container
    ->get('jwt.authentication.jwt');
  foreach ([
    'Authorization',
    'JWT-Authorization',
  ] as $header) {
    $request = Request::create('/');
    $request->headers
      ->set($header, 'Bearer ' . $token);
    $this
      ->assertTrue($auth_service
      ->applies($request));
    $user = $auth_service
      ->authenticate($request);
    $this
      ->assertEqual($account
      ->id(), $user
      ->id());

    // When blocked the account is no longer valid.
    $account
      ->block()
      ->save();
    $result = $auth_service
      ->authenticate($request);
    $this
      ->assertNull($result, 'User is blocked.');
    $account
      ->activate()
      ->save();
  }
}