0

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.

0

What happens if you replace:

requirements:
  _method: 'POST'
  _custom_access_check: 'TRUE'

With:

requirements:
  _method: 'POST'
  _permission: 'access content'

Any then remove your CustomAccessCheck code

  • When I do so, I can access the page only if I have 'access content' permission. That's ok when I'm logged in as Admin. But I want to access the page from my third-party app using drupal credentials in POST request – Patrick Star Apr 1 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.