Block caching not working for anonymous users despite setting cache contexts
The issue was that I had different render arrays set depending on whether the user was logged in or not, but the cache context only applied to one of the render arrays but not the other. If I have different possible render arrays being returned every single one needs to have the cache settings added.

I resolved the issue by changing my code to

if ($user-&gt;hasRole('anonymous')) {
        if ($loginrequired) {
            $content = [
                '#markup' =&gt; '&lt;p&gt; Login required. &lt;a href="/user/login"&gt;Click Here to Login&lt;/a&gt;&lt;/p&gt;',
                '#cache'   =&gt; [
                     'max-age' =&gt; 0,
                     'contexts' =&gt; ['url.path']
                 ],
            ];
            return $content;
        }
}
$content = [
    'header'   =&gt; [
        '#markup' =&gt; $header_text,
    ],
    '#cache'   =&gt; [
        'max-age' =&gt; 0,
        'contexts' =&gt; ['url.path']
    ],
    $webform,
];
return $content;