Skip to content

Instantly share code, notes, and snippets.

@vishwac09
Last active June 25, 2022 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishwac09/9c7d4a385a4e0b6f9c2a985c3d96a8fb to your computer and use it in GitHub Desktop.
Save vishwac09/9c7d4a385a4e0b6f9c2a985c3d96a8fb to your computer and use it in GitHub Desktop.
Drupal8 AuthenticationProvider Example
<?php
namespace Drupal\rest_auth\Authentication;
use Drupal\Core\Authentication\AuthenticationProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Session\UserSession;
use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* Authentication provider to validate requests with x-api-key directive in header.
*/
class RestAuth implements AuthenticationProviderInterface {
/**
* {@inheritdoc}
*/
public function applies(Request $request) {
/**
* Buy default the authentication plugin will be triggered on all routes/paths
* visited by the user. For HTML pages we do not want to this authentictor to
* execute, but executed maily for REST API reqests.
* Hence we should allow this authenticator to verify the header value only on those routes/paths
* when it is present. This functions returns bool (true/false), if true below authenticate function will be
* executed else 403 Forbidden.
*/
return $request->headers->has('x-api-key');
}
/**
* {@inheritdoc}
*/
public function authenticate(Request $request) {
/**
* Return user account data if the header value matches.
*/
if ($request->headers->get('x-api-key') == 'some-value') {
// Pseudo logic to decode JWT token, although this is similar to the original logic.
$userInfo = JWT::decode($request->headers->get('userinfo));
$email = $userInfo['email'];
// Return the user object.
$user = user_load_mail($email);
if (!$user) {
throw new HttpException(400, 'Incorrect user');
}
return $user;
} else {
return new HttpException(400, 'Specified x-api-key value is incorrect');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment