I'm working on module that should behave as API endpoint.
I created Controller which handler POST & GET requests from external system, but I need to add user authentication so only authenticated user can acccess these endpoints.
My mymodule.routing.yml:
mymodule.show_content:
path: 'api/getContent'
defaults:
_controller: '\Drupal\mymodule\Controller\ContentController::getContent'
_format: hal_json
requirements:
_method: 'POST'
_custom_access_check: 'TRUE'
My mymodule/src/Access/CustomAccessCheck.php:
class CustomAccessCheck implements AccessInterface
{
public function access(AccountInterface $account)
{
return ($account->hasPermission('access content')) ? AccessResult::allowed() : AccessResult::forbidden();
}
}
My mymodule.services.yml:
mymodule.custom_access_check:
class: Drupal\mymodule\Access\CustomAccessCheck
arguments: ['@current_user']
tags:
- { name: access_check, applies_to: _custom_access_check }
I created a user called REST with REST
role. I gave him 'access content' permission and tried to make request with Postman using POST method and following headers:
{
Content-Type: application/hal+json,
Authorization: Basic <base64_encoded user:pass>
X-CSRF-Token: token obtained from <page_url>/rest/session/token
}
When I make request with admin user, I see in recent logs, that admin access the route /api/getContent but access was denied. When I use my REST user it logs as anonymous user. Even when I log the status of authentication inside CustomAccessCheck::access function I see that user is authenticated with TRUE
I need to keep this authentication separated (out of controller, in service or something) because I need to authenticate every request (re-use auth) so only internal users can use API (and not everyone with URL). I don't understand what is missing and why only my admin user is recognized by drupal and the REST user not.