SimpleOauthAuthenticationProvider.php in Simple OAuth (OAuth2) & OpenID Connect 8
File
src/Authentication/Provider/SimpleOauthAuthenticationProvider.php
View source
<?php
namespace Drupal\simple_oauth\Authentication\Provider;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\simple_oauth\Authentication\TokenAuthUser;
use Symfony\Component\HttpFoundation\Request;
class SimpleOauthAuthenticationProvider implements SimpleOauthAuthenticationProviderInterface {
protected $configFactory;
protected $entityManager;
public function __construct(ConfigFactoryInterface $config_factory, EntityManagerInterface $entity_manager) {
$this->configFactory = $config_factory;
$this->entityManager = $entity_manager;
}
public function applies(Request $request) {
return (bool) $this::getTokenValue($request);
}
public static function getTokenValue(Request $request) {
$auth_header = $request->headers
->get('Authorization', '', TRUE);
$prefix = 'Bearer ';
if (strpos($auth_header, $prefix) === 0) {
return substr($auth_header, strlen($prefix));
}
$ct_header = $request->headers
->get('Content-Type', '', TRUE);
$is_get = $request
->getMethod() == Request::METHOD_GET;
$token = $request->request
->get('access_token');
if (!$is_get && $ct_header == 'application/x-www-form-urlencoded' && $token) {
return $token;
}
return NULL;
}
public function authenticate(Request $request) {
$token_storage = $this->entityManager
->getStorage('access_token');
$ids = $token_storage
->getQuery()
->condition('value', $this::getTokenValue($request))
->condition('expire', REQUEST_TIME, '>')
->range(0, 1)
->execute();
if (!empty($ids)) {
$token = $token_storage
->load(reset($ids));
try {
return new TokenAuthUser($token);
} catch (\Exception $e) {
}
}
return [];
}
}