View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.httpclient;
16  
17  import org.apache.http.cookie.ClientCookie;
18  import org.apache.http.cookie.CommonCookieAttributeHandler;
19  import org.apache.http.cookie.Cookie;
20  import org.apache.http.cookie.CookieOrigin;
21  import org.apache.http.cookie.CookieRestrictionViolationException;
22  import org.apache.http.cookie.MalformedCookieException;
23  import org.apache.http.cookie.SetCookie;
24  import org.apache.http.impl.cookie.BasicClientCookie;
25  import org.htmlunit.util.StringUtils;
26  
27  /**
28   * Customized CookieAttributeHandler for handling of the samesite attribute.
29   *
30   * @author Ronald Brill
31   */
32  final class HtmlUnitSameSiteHandler implements CommonCookieAttributeHandler {
33  
34      /** The name of the attribute. */
35      static final String SAMESITE_ATTR = "samesite";
36  
37      /**
38       * {@inheritDoc}
39       * Like the browsers, a cookie with 'SameSite=None' has to be secure.
40       */
41      @Override
42      public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException {
43          if (cookie instanceof ClientCookie clientCookie
44                  && "none".equalsIgnoreCase(clientCookie.getAttribute(SAMESITE_ATTR))
45                  && !cookie.isSecure()) {
46              throw new CookieRestrictionViolationException(
47                      "Cookie '" + cookie.getName() + "' with 'SameSite=None' requires the 'secure' attribute");
48          }
49      }
50  
51      @Override
52      public void parse(final SetCookie cookie, final String value) throws MalformedCookieException {
53          ((BasicClientCookie) cookie).setAttribute(SAMESITE_ATTR, StringUtils.toRootLowerCase(value));
54      }
55  
56      @Override
57      public boolean match(final Cookie cookie, final CookieOrigin origin) {
58          return true;
59      }
60  
61      @Override
62      public String getAttributeName() {
63          return SAMESITE_ATTR;
64      }
65  }