When working with data that expects authenticated users, the authentication service provider should also provide a page cache service handler. Services that are tagged with page_cache_request_policy have the ability to check whether the content is cached or not. This prevents authorization requests from being cached.
The following code is taken from the basic_auth module:
basic_auth.page_cache_request_policy.disallow_basic_auth_requests:
class: Drupal\basic_auth\PageCache\DisallowBasicAuthRequests
public: false
tags:
- { name: page_cache_request_policy }
The \Drupal\basic_auth\PageCache\DisallowBasicAuthRequests class implements the \Drupal\Core\PageCache\RequestPolicyInterface interface. The check method allows the page cache policy to explicitly deny or remain neutral on a page's ability to be cached. The basic_auth module checks whether the default authentication headers are present. For the simple_oauth module, it checks whether a valid token is present.
This is an important security measure if you are implementing your own authentication services.
A page cache policy service can be implemented by creating a class in your module's PageCache namespace and implementing the \Drupal\Core\PageCache\ResponsePolicyInterface interface. Then, we need to register the class as a service in your module's services.yml.