只能从响应中设置jessessionId cookie的Samesite [英] Samesite for jessessionId cookie can be set only from response

查看:140
本文介绍了只能从响应中设置jessessionId cookie的Samesite的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试不设置相同站点;从java过滤器中获取我的jsessionid cookie的安全性.我已经在响应集cookie标头中添加了它.更改之后,请求cookie jsessionId是相同的.在响应中,使用Samesite属性None和secure修改了jsessionId.如果请求的jsessionId cookie保持不变,它将正常工作.

I am trying to set samesite none; secure for my jsessionid cookie from java filter . I have added this in response set cookie header.After this change the request cookie jsessionId is same . In the response the jsessionId is modified with Samesite attribute None and secure. Will it work if the request jsessionId cookie remains unchanged.

推荐答案

对ServletResponse方法的调用:sendError,getWrite.flush(),sendRedirect,getOutputStream.Flush提交响应,这意味着将在更新Set-cookie标头之前写入状态代码和标头. ServletResponse .

解决方案1:您可以将过滤器放置在可能导致上述方法调用的任何过滤器之前,并在调用filterChain.doFilter之前修改标头

Solution 1 : you can place your filter before any filter which could cause a call to the method mentioned above and modify the headers before the call to filterChain.doFilter

解决方案2:拦截该方法的调用并在提交响应之前更新标头.

Solution 2 : Intercept calls to this method and update headers before the response is committed.

    package com.cookie.example.filters.cookie;
    
    
    import com.google.common.net.HttpHeaders;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.InitializingBean;
    import org.springframework.web.filter.DelegatingFilterProxy;
    
    import javax.annotation.Nonnull;
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpServletResponseWrapper;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.List;
    
    /**
     * Implementation of an HTTP filter {@link Filter} which which allow customization of {@literal Set-Cookie} header.
     * customization is delegated to implementations of {@link CookieHeaderCustomizer}
     */
    public class CookieHeaderCustomizerFilter extends DelegatingFilterProxy implements InitializingBean {
    
      private final List<CookieHeaderCustomizer> cookieHeaderCustomizers;
    
      @Override
      public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        if(CollectionUtils.isEmpty(cookieHeaderCustomizers)){
          throw new IllegalArgumentException("cookieHeaderCustomizers is mandatory");
        }
      }
    
      public CookieHeaderCustomizerFilter(final List<CookieHeaderCustomizer> cookieHeaderCustomizers) {
        this.cookieHeaderCustomizers = cookieHeaderCustomizers;
      }
    
      public CookieHeaderCustomizerFilter() {
        this.cookieHeaderCustomizers = Collections.emptyList();
      }
    
    
      /** {@inheritDoc} */
      public void destroy() {
      }
    
      /** {@inheritDoc} */
      public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    
        if (!(request instanceof HttpServletRequest)) {
          throw new ServletException("Request is not an instance of HttpServletRequest");
        }
    
        if (!(response instanceof HttpServletResponse)) {
          throw new ServletException("Response is not an instance of HttpServletResponse");
        }
    
        chain.doFilter(request, new CookieHeaderResponseWrapper((HttpServletRequest) request, (HttpServletResponse)response ));
    
      }
    
    
      /**
       * An implementation of the {@link HttpServletResponse} which customize {@literal Set-Cookie}
       */
      private class CookieHeaderResponseWrapper extends HttpServletResponseWrapper{
    
        @Nonnull private final HttpServletRequest request;
    
        @Nonnull private final HttpServletResponse response;
    
    
        public CookieHeaderResponseWrapper(@Nonnull final HttpServletRequest req, @Nonnull final HttpServletResponse resp) {
          super(resp);
          this.request = req;
          this.response = resp;
    
        }
    
        /** {@inheritDoc} */
        @Override
        public void sendError(final int sc) throws IOException {
          applyCustomizers();
          super.sendError(sc);
        }
    
        /** {@inheritDoc} */
        @Override
        public PrintWriter getWriter() throws IOException {
          applyCustomizers();
          return super.getWriter();
        }
    
        /** {@inheritDoc} */
        @Override
        public void sendError(final int sc, final String msg) throws IOException {
          applyCustomizers();
          super.sendError(sc, msg);
        }
    
        /** {@inheritDoc} */
        @Override
        public void sendRedirect(final String location) throws IOException {
          applyCustomizers();
          super.sendRedirect(location);
        }
    
        /** {@inheritDoc} */
        @Override
        public ServletOutputStream getOutputStream() throws IOException {
          applyCustomizers();
          return super.getOutputStream();
        }
    
        private void applyCustomizers(){
    
          final Collection<String> cookiesHeaders = response.getHeaders(HttpHeaders.SET_COOKIE);
    
          boolean firstHeader = true;
    
          for (final String cookieHeader : cookiesHeaders) {
    
            if (StringUtils.isBlank(cookieHeader)) {
              continue;
            }
    
            String customizedCookieHeader = cookieHeader;
    
            for(CookieHeaderCustomizer cookieHeaderCustomizer : cookieHeaderCustomizers){
    
              customizedCookieHeader = cookieHeaderCustomizer.customize(request, response, customizedCookieHeader);
    
            }
    
            if (firstHeader) {
              response.setHeader(HttpHeaders.SET_COOKIE,customizedCookieHeader);
              firstHeader=false;
            } else {
              response.addHeader(HttpHeaders.SET_COOKIE, customizedCookieHeader);
            }
    
          }
    
        }
    
      }
    
    }



  /**
   * Implement this interface and inject add it to {@link SameSiteCookieHeaderCustomizer}
   */
    public interface CookieHeaderCustomizer {
      String customize(@Nonnull final HttpServletRequest request, @Nonnull final HttpServletResponse response, @Nonnull final String cookieHeader);
    }


  package com.cookie.example.filters.cookie;
  
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  
  import javax.annotation.Nonnull;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  
  /**
    *Add SameSite attribute if not already exist
    *SameSite attribute value is defined by property "cookie.sameSite"
   */
  public class SameSiteCookieHeaderCustomizer implements CookieHeaderCustomizer {
  
    private static final Logger LOGGER = LoggerFactory.getLogger(SameSiteCookieHeaderCustomizer.class);
  
    private static final String SAME_SITE_ATTRIBUTE_NAME ="SameSite";
  
    private static final String SECURE_ATTRIBUTE_NAME="Secure";
  
    private final SameSiteValue sameSiteValue;
  
    public SameSiteCookieHeaderCustomizer(SameSiteValue sameSiteValue) {
      this.sameSiteValue = sameSiteValue;
    }
  
  
    @Override
    public String customize(@Nonnull final HttpServletRequest request, @Nonnull final HttpServletResponse response, @Nonnull final String cookieHeader) {
      StringBuilder sb = new StringBuilder(cookieHeader);
      if (!cookieHeader.contains(SAME_SITE_ATTRIBUTE_NAME)) {
        sb.append("; ").append(SAME_SITE_ATTRIBUTE_NAME).append("=").append(sameSiteValue.value);
      }
      if(SameSiteValue.None == sameSiteValue && !cookieHeader.contains(SECURE_ATTRIBUTE_NAME)){
        sb.append("; ").append(SECURE_ATTRIBUTE_NAME);
      }
      return sb.toString();
    }
  
    public enum SameSiteValue{
  
      /**
       * Send the cookie for 'same-site' requests only.
       */
      Strict("Strict"),
      /**
       * Send the cookie for 'same-site' requests along with 'cross-site' top
       * level navigations using safe HTTP methods (GET, HEAD, OPTIONS, and TRACE).
       */
      Lax("Lax"),
      /**
       * Send the cookie for 'same-site' and 'cross-site' requests.
       */
      None("None");
  
      /** The same-site attribute value.*/
      private String value;
  
      /**
       * Constructor.
       *
       * @param attrValue the same-site attribute value.
       */
      SameSiteValue(@Nonnull final String attrValue) {
        value = attrValue;
      }
  
      /**
       * Get the same-site attribute value.
       *
       * @return Returns the value.
       */
      public String getValue() {
        return value;
      }
  
    }
  
  }

这篇关于只能从响应中设置jessessionId cookie的Samesite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆