【问题标题】:How to flag a cookie as secure which are not part of session in tomcat如何将不属于tomcat会话一部分的cookie标记为安全的
【发布时间】:2021-10-25 06:35:55
【问题描述】:

在我们的一个应用程序中,我们的跨域 cookie 在 chrome 中不起作用,因为该 cookie 不安全,也不是仅限 HTTP。该 cookie 是由该工具生成的,我们对此没有太多控制权。

我们尝试了多种方法来解决这个问题。

  1. 尝试在 web.xml 文件中设置以下配置,但由于不在会话中,因此无法正常工作。

    <session-config>
         <session-timeout>60</session-timeout>
         <cookie-config>
             <http-only>true</http-only>
             <secure>true</secure>
         </cookie-config>
     </session-config>
    
  2. 在 context.xml 中也尝试了&lt;CookieProcessor sameSiteCookies="none" /&gt; 以及其他属性,但没有运气。

请查找附件图片以供参考。

【问题讨论】:

    标签: google-chrome tomcat cookies


    【解决方案1】:

    &lt;cookie-config&gt; 仅适用于用于建立会话的 cookie(默认为JSESSIONID)。

    如果您的应用程序设置的 cookie 没有 securehttpOnly 属性,您可以使用 Filter 进行更正:

    public class SecureCookieServletFilter implements Filter {
    
       private static class SecureCookieResponseWrapper extends HttpServletResponseWrapper {
    
          public SecureCookieResponseWrapper(HttpServletResponse response) {
             super(response);
          }
    
          @Override
          public void addCookie(Cookie cookie) {
             cookie.setSecure(true);
             cookie.setHttpOnly(true);
             super.addCookie(cookie);
          }
    
       }
       @Override
       public void init(FilterConfig filterConfig) throws ServletException {
          // NOP
       }
    
       @Override
       public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
          final ServletResponse response = res instanceof HttpServletResponse ? new SecureCookieResponseWrapper((HttpServletResponse) res) : res;
          chain.doFilter(req, response);
       }
    
       @Override
       public void destroy() {
          // NOP
       }
    
    }
    

    当然,您可以在自定义 CookieProcessor 中实现相同的逻辑,但这会更难分发。

    【讨论】:

      猜你喜欢
      • 2015-12-23
      • 2012-07-30
      • 2012-12-04
      • 2012-04-15
      • 2018-09-08
      • 2021-12-03
      • 2018-12-04
      • 2023-03-12
      • 2018-10-10
      相关资源
      最近更新 更多