Follow this step-by-step guide to create a secure API in Drupal using bearer token authentication with the Simple OAuth module.
First, you need to install the simple_oauth
module and its dependencies:
composer require drupal/simple_oauth
Then, enable the module:
drush en simple_oauth -y
Simple OAuth requires public and private keys to sign tokens. You can generate these using OpenSSL:
mkdir -p sites/default/files/keys
openssl genrsa -out sites/default/files/keys/private.key 2048
openssl rsa -in sites/default/files/keys/private.key -pubout > sites/default/files/keys/public.key
Ensure these keys are not accessible via the web by updating your .htaccess
or web server configuration.
Navigate to /admin/config/people/simple_oauth and enter the paths to your public and private keys.
Navigate to /admin/config/people/simple_oauth/oauth2_client and add a new OAuth2 client with a client ID and secret.
Edit CustomApiController.php
:
<?php
namespace Drupal\custom_api\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\simple_oauth\Authentication\Provider\SimpleOauthAuthenticationProvider;
class CustomApiController extends ControllerBase {
protected $authProvider;
public function __construct(SimpleOauthAuthenticationProvider $authProvider) {
$this->authProvider = $authProvider;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('simple_oauth.authentication.simple')
);
}
public function content(Request $request) {
$authenticated = $this->authProvider->applies($request) && $this->authProvider->authenticate($request);
if ($authenticated) {
$data = [
'message' => 'Authenticated API response',
'status' => 'success',
];
} else {
$data = [
'message' => 'Access Denied',
'status' => 'error',
];
return new JsonResponse($data, 403);
}
return new JsonResponse($data);
}
}
Ensure that the route in custom_api.routing.yml
has appropriate permissions:
custom_api.content:
path: '/api/custom'
defaults:
_controller: '\Drupal\custom_api\Controller\CustomApiController::content'
_title: 'Custom API'
requirements:
_permission: 'access content'
options:
_auth:
- bearer
_format: 'json'
To get a bearer token, send a POST request to /oauth/token
with the client credentials:
curl -X POST http://your-drupal-site/oauth/token \
-d "grant_type=password&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&username=YOUR_USERNAME&password=YOUR_PASSWORD"
Use the token to access your API endpoint:
curl -X GET http://your-drupal-site/api/custom \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
By following these steps, you can secure your Drupal API using bearer token authentication. This setup ensures that only authenticated users can access the API, providing an additional layer of security.
Published By: Krishanu Jadiya
Updated at: 2024-08-06 00:04:50