How do you configure HttpOnly cookies in tomcat / java webapps?

后端 未结 9 1014
迷失自我
迷失自我 2020-11-27 10:47

After reading Jeff\'s blog post on Protecting Your Cookies: HttpOnly. I\'d like to implement HttpOnly cookies in my web application.

How do you tell tomcat to use ht

9条回答
  •  一向
    一向 (楼主)
    2020-11-27 11:12

    In Tomcat6, You can conditionally enable from your HTTP Listener Class:

    public void contextInitialized(ServletContextEvent event) {                 
       if (Boolean.getBoolean("HTTP_ONLY_SESSION")) HttpOnlyConfig.enable(event);
    }
    

    Using this class

    import java.lang.reflect.Field;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import org.apache.catalina.core.StandardContext;
    public class HttpOnlyConfig
    {
        public static void enable(ServletContextEvent event)
        {
            ServletContext servletContext = event.getServletContext();
            Field f;
            try
            { // WARNING TOMCAT6 SPECIFIC!!
                f = servletContext.getClass().getDeclaredField("context");
                f.setAccessible(true);
                org.apache.catalina.core.ApplicationContext ac = (org.apache.catalina.core.ApplicationContext) f.get(servletContext);
                f = ac.getClass().getDeclaredField("context");
                f.setAccessible(true);
                org.apache.catalina.core.StandardContext sc = (StandardContext) f.get(ac);
                sc.setUseHttpOnly(true);
            }
            catch (Exception e)
            {
                System.err.print("HttpOnlyConfig cant enable");
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题