无法为春季启动1.5.22设置Cookie samesite = none

时间:2020-09-24 18:32:18

标签: spring-boot spring-security-oauth2 samesite

我正在使用Spring Boot 1.5.22,但我遇到了cookie samesite = none proporty的问题。我无法为cookie设置samesite属性,因此oauth身份验证不适用于chrome,但是它正在其他浏览器上运行。因此,我尝试了几种解决方案。

@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        if (container instanceof TomcatEmbeddedServletContainerFactory) {
            TomcatEmbeddedServletContainerFactory factory = TomcatEmbeddedServletContainerFactory.class.cast(container);
            factory.addContextCustomizers(new TomcatContextCustomizer() {
                @Override
                void customize(Context context) {
                    Rfc6265CookieProcessor cookieProcessor = new Rfc6265CookieProcessor()
                    cookieProcessor.setSameSiteCookies("None")
                    context.setCookieProcessor(cookieProcessor)
                }

            })
        }
    }
}

那没有帮助。所以我尝试添加自定义过滤器

@Component
public class SameSiteFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, response);
        addSameSiteCookieAttribute((HttpServletResponse) response);
    }

    private void addSameSiteCookieAttribute(HttpServletResponse response) {
        Collection<String> headers = response.getHeaders(HttpHeaders.SET_COOKIE);
        boolean firstHeader = true;
        for (String header : headers)
 {

            if (firstHeader) {
                response.setHeader(HttpHeaders.SET_COOKIE, String.format("%s; %s", header, "SameSite=None;"));
                firstHeader = false;
                continue;
            }
            response.addHeader(HttpHeaders.SET_COOKIE, String.format("%s; %s", header, "SameSite=None;"));
        }
    }

    @Override
    public void destroy() {

    }
}

我将此添加为addFilterBefore(new SameSiteFilter(),BasicAuthenticationFilter.class)和addFilterAfter(new SameSiteFilter(),BasicAuthencticationFilter.class) 在HttpSecurity配置中

无论如何为jsessionid设置SameSite = None

1 个答案:

答案 0 :(得分:0)

我正在使用嵌入式tomcat 8.54,它没有将samesite设置为none,而是为其他值(例如lax,strict)工作。所以更新了嵌入式tomcat到8.58,我想他们已经修复了该错误。所以,更新tomcat版本解决了我的问题