Java应用程序中的SameSite cookie

问题描述 投票:18回答:2

你知道任何允许为cookie设置自定义标志的Java cookie实现,比如SameSite=strict吗?似乎javax.servlet.http.Cookie有一套严格限制的标志可以添加。

java cookies csrf flags
2个回答
31
投票

我不是JEE专家,但我认为因为cookie属性是一个有点新的发明,所以你不能指望它出现在Java EE 7接口或实现中。正如看起来那样,Cookie类缺少一个通用属性的setter。但不是将cookie添加到你的HttpServletResponse通过

response.addCookie(myCookie)

您只需通过设置相应的HTTP标头字段即可

response.setHeader("Set-Cookie", "key=value; HttpOnly; SameSite=strict")

2
投票

如果您不想更新所有代码,您也可以使用Apache或Nginx配置(或您正在使用的任何其他HTTP服务器/代理)通过一行配置实现相同的操作

1 Setting SameSite cookies using Apache configuration

您可以将以下行添加到Apache配置中

Header always edit Set-Cookie (.*) "$1; SameSite=Lax"

这将使用SameSite=Lax标志更新所有cookie

在这里查看更多:https://blog.giantgeek.com/?p=1872

2 Setting SameSite cookies using Nginx configuration

location / {
    # your usual config ...
    # hack, set all cookies to secure, httponly and samesite (strict or lax)
    proxy_cookie_path / "/; secure; HttpOnly; SameSite=strict";
}

同样在这里,这也将使用SameSite=Lax标志更新所有cookie

在这里查看更多:https://serverfault.com/questions/849888/add-samesite-to-cookies-using-nginx-as-reverse-proxy

© www.soinside.com 2019 - 2024. All rights reserved.