在 Java Web 应用程序中为设置 cookie 添加 httponly 和安全标志

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34489406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:42:19  来源:igfitidea点击:

adding httponly and secure flag for set cookie in java web application

javasecurityfilterstruts2web.xml

提问by keval

I want to add the httponlyand secureflags for Cookies. To implement it, I am using Filterswhich are configured in web.xml.

我想为 Cookie添加httponlysecure标志。为了实现它,我正在使用Filtersweb.xml.

The code for adding flags is as below:

添加标志的代码如下:

package com.crisil.dbconn;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.filters.SecurityWrapperResponse;

public class ClickHymanFilter implements Filter 
{

    private String mode = "DENY";

    /**
     * Add X-FRAME-OPTIONS response header to tell IE8 (and any other browsers who
     * decide to implement) not to display this content in a frame. For details, please
     * refer to http://blogs.msdn.com/sdl/archive/2009/02/05/clickHymaning-defense-in-ie8.aspx.
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse)response;
        //HttpServletRequest req = (HttpServletRequest)request.getSession();


        res.addHeader("X-FRAME-OPTIONS", mode );
        res.addHeader("X-Content-Type-OPTIONS", "nosniff" );
        res.addHeader("X-XSS-Protection", "1; mode=block" );
        res.addHeader("Vary", "*" );
        res.addHeader("Expires", "-1" );
        res.addHeader("Pragma", "no-cache" );
        res.addHeader("Cache-control", "no-cache, no-store,max-age=0, must-revalidate" );
        String contextPath = ((HttpServletRequest) request).getContextPath()+"kevalcccc";
       ((HttpServletResponse)ServletActionContext.getResponse()).setHeader("SET-COOKIE",  "JSESSIONID=" + ((HttpServletRequest)request).getSession().getId() + ";Path="+contextPath+";Secure;HttpOnly");
     // touch the session
       // ((HttpServletRequest) request).getSessison();
       // System.out.println("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");

        // overwriting the cookie with Secure attribute set
       // ((HttpServletResponse)response).setHeader("Set-Cookie", "JSESSIONID=" + ((HttpServletRequest)request).getSession().getId() + ";Path=/");

        ////////////

       /* Cookie[] cookies = ((HttpServletRequest) request).getCookies();
        if (cookies != null)
            for (int i = 0; i < cookies.length; i++) {
                cookies[i].setValue("");
                cookies[i].setPath("/");
                cookies[i].setMaxAge(0);
                cookies[i].setSecure(true);
                res.addCookie(cookies[i]);
            }
        */
        //////////////
        String sessionid = ((HttpServletRequest) request).getSession().getId();
        ((HttpServletResponse) response).setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; HttpOnly");

        chain.doFilter(request, response);
    }

    public void destroy() {
    }

    public void init(FilterConfig filterConfig) {
        String configMode = filterConfig.getInitParameter("mode");
        if ( configMode != null ) {
            mode = configMode;
        }
    }

}

The above code is adding httponlyand secureflags for the JSESSIONID cookie. However, in the Response Header, I am getting two cookies. The second one does not have httponlyand secureflags set. Please refer to the below output:

上面的代码是为 JSESSIONID cookie添加httponlysecure标记。但是,在响应标头中,我收到了两个 cookie。第二个没有设置httponlysecure标志。请参考以下输出:

JSESSIONID=1dbLWQ6WYBHJ93Tv7TfQ2fdLgjRp2pQBsVxQVZ2WBQkYwB60wg43!1248935162!1451244054765; HttpOnly;Secure

JSESSIONID=1dbLWQ6WYBHJ93Tv7TfQ2fdLgjRp2pQBsVxQVZ2WBQkYwB60wg43!1248935162; path=/"

JSESSIONID=1dbLWQ6WYBHJ93Tv7TfQ2fdLgjRp2pQBsVxQVZ2WBQkYwB60wg43!1248935162!1451244054765; HttpOnly;安全

JSESSIONID=1dbLWQ6WYBHJ93Tv7TfQ2fdLgjRp2pQBsVxQVZ2WBQkYwB60wg43!1248935162; 路径=/"

Why are the httponlyand secureflags not added for the second cookie?

为什么没有为第二个 cookie 添加httponlysecure标志?

回答by heenenee

Setting the JSESSIONIDis the responsibility of whatever servlet container is running your web application. Remove the setHeaderfrom your filter, and configure your web application properly by adding the following to your web.xml:

设置JSESSIONID是运行 Web 应用程序的任何 servlet 容器的责任。setHeader从您的过滤器中删除,并通过将以下内容添加到您的 中来正确配置您的 Web 应用程序web.xml

<session-config>
    <cookie-config>
        <http-only>true</http-only>
        <secure>true</secure>
    </cookie-config>
</session-config>

回答by Alireza Fattahi

If your webserver not support it you must do it your self.

如果您的网络服务器不支持它,您必须自己做。

A good answer could be found at: How do you configure HttpOnly cookies in tomcat / java webapps?

可以在以下位置找到一个很好的答案:How do you configure HttpOnly cookies in tomcat / java webapps?