In my application, I want anonymous users to be able to view an unpublished node but only if they append a special code to the URL. For example:
www.mysite.com/node/123?code=Hx23ufG38
I figure I can do something in a preprocess function to check if the code is appended to the URL and, if so, allow the user to view the unpublished node. (This clearly is not for a use case where the content is sensitive, because anyone visiting the page at the URL with the code appended will be able to see the page.)
How can I programmatically grant the current (anonymous) user permission to view unpublished content, provided the condition is met in the URL?
This is for a Drupal 9 website.
hook_entity_access
(orhook_ENTITY_TYPE_access
), and add a query string cache context to theAccessResult
you return from there->addCacheContexts(['url.query_args:code'])
. Otherwise the first anonymous user with query string will grant access for all other anonymous users following.