JwtPathAuth.php in JSON Web Token Authentication (JWT) 8
File
modules/jwt_path_auth/src/Authentication/Provider/JwtPathAuth.php
View source
<?php
namespace Drupal\jwt_path_auth\Authentication\Provider;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\PageCache\ResponsePolicy\KillSwitch;
use Drupal\jwt\Transcoder\JwtTranscoderInterface;
use Drupal\jwt\Transcoder\JwtDecodeException;
use Drupal\Core\Authentication\AuthenticationProviderInterface;
use Symfony\Component\HttpFoundation\Request;
class JwtPathAuth implements AuthenticationProviderInterface {
protected $transcoder;
protected $configFactory;
protected $entityTypeManager;
protected $killSwitch;
public function __construct(JwtTranscoderInterface $transcoder, ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, KillSwitch $killSwitch) {
$this->transcoder = $transcoder;
$this->configFactory = $config_factory;
$this->entityTypeManager = $entity_type_manager;
$this->killSwitch = $killSwitch;
}
public function applies(Request $request) {
$raw_jwt = $request->query
->get('jwt');
if (empty($raw_jwt)) {
return FALSE;
}
$config = $this->configFactory
->get('jwt_path_auth.config');
$allowed_path_prefixes = (array) $config
->get('allowed_path_prefixes');
$path_matched = FALSE;
$request_path = $request
->getPathInfo();
foreach ($allowed_path_prefixes as $prefix) {
if (strpos($request_path, $prefix) === 0) {
$path_matched = TRUE;
break;
}
}
return $path_matched;
}
public function authenticate(Request $request) {
$raw_jwt = $request->query
->get('jwt');
try {
$jwt = $this->transcoder
->decode($raw_jwt);
} catch (JwtDecodeException $e) {
return NULL;
}
$uid = $jwt
->getClaim([
'drupal',
'path_auth',
'uid',
]);
$path = $jwt
->getClaim([
'drupal',
'path_auth',
'path',
]);
$request_path = $request
->getBaseUrl() . $request
->getPathInfo();
if ($uid && $path && strpos($request_path, $path) === 0) {
$user = $this->entityTypeManager
->getStorage('user')
->load($uid);
if ($user && !$user
->isBlocked()) {
$this->killSwitch
->trigger();
return $user;
}
}
return NULL;
}
}