如何以编程方式在cookie上设置安全标志 [英] How to set secure flag on cookie programatically
问题描述
我知道我们可以这样做:
I know we can do something like this:
<session-config>
<cookie-config>
<secure>true</secure>
</cookie-config>
</session-config>
但我想要实现的是根据某些配置设置此标志(true或false)。
But what I want to achieve is to set this flag (true or false) based on some config.
我们应该使用过滤器吗?
Should we use a filter and how ?
谢谢
推荐答案
假设您使用的是servlet 3.0+环境,你不想使用 web.xml
来指定cookie-secure-flag但是以编程方式设置它:
Assuming that you are in a servlet 3.0+ environment, and you don't want to use web.xml
to specify the cookie-secure-flag but set it programmatically:
实施 ServletContextListener 并在其中注册 web.xml
或通过注释。
在其 contextInitialized
方法中评估您的安全标志您的配置并将其设置在 SessionCookieConfig
:
Implement a ServletContextListener and register it in the web.xml
or via annotation.
In its contextInitialized
method evaluate your secure flag from your config and set it on the SessionCookieConfig
:
public void contextInitialized(ServletContextEvent sce) {
boolean secure = ...
sce.getServletContext().getSessionCookieConfig().setSecure(secure);
}
这篇关于如何以编程方式在cookie上设置安全标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!