0

I have a custom module which implements hook_ENTITY_TYPE_access to control access to particular PDFs (media objects). When the user doesn't have access they are redirected to a login/register page. This works successfully.

I now need to send specific HTTP response headers (cache-control, no-store) along with the response when the user does have access to the document.

From what I have been able to find, to get access to the response object and add headers I need to subscribe to the response event. This seems excessive, I'm subscribing to the response event for every request, when I only need the to set headers for a very small number of requests.

Do I need to subscribe to the response event, is there a way to get hold of the response object when processing hook_ENTITY_TYPE_access?

Or, is there another way to set 'Cache-control: no-store' without needing to access the response object?

Is it a fair assumption, that when hook_ENTITY_TYPE_access has been called and allowed access, that any later response must be for the particular media object. I.e., I need some way for the hook_ENTITY_TYPE_access handler and the response event subscriber to communicate, e.g. in the hook handler, retrieve my event subscriber service object and set some flag on it - to indicate it should add headers to the response event.

Or, Should I be looking at this another way?

1 Answer 1

0

Yes, there is a way to communicate via cache metadata. If you add cache metadata to the access results the router adds it to a CacheableAccessDeniedHttpException. When issuing the redirect response to the login/register page you can check if the exception class is an instance of CacheableDependencyInterface and get the cache metadata to set the response headers.

2
  • Thanks for answering. Maybe I'm missing something, that enables me to set cache tags, cache contexts and/or max age. None of which will get me a cache-control header with no-store. For the redirect (on denied) I don't need need to set any headers. no-store needs to be set when access is allowed.
    – Chris
    Dec 15, 2023 at 7:53
  • Then the cache metadata ends up in the cacheable response. It should be possible to decide whether to add the no-store header based on the current route and the cache metadata. It would be best if you add the correct cache metadata anyway to define the cacheability of inbound routes and outbound links within Drupal, independently of the headers you are sending.
    – 4uk4
    Dec 15, 2023 at 8:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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