Setting an httponly cookie with javax.servlet 2.5

冷暖自知 提交于 2019-11-28 06:25:20

You are right, manually setting header is the right way to achive your goal.

You can also use javax.ws.rs.core.NewCookie or any other class with useful toString method to print cookie to a header to make things more simple.

public static String getHttpOnlyCookieHeader(Cookie cookie) {

    NewCookie newCookie = new NewCookie(cookie.getName(), cookie.getValue(), 
            cookie.getPath(), cookie.getDomain(), cookie.getVersion(), 
            cookie.getComment(), cookie.getMaxAge(), cookie.getSecure());

    return newCookie + "; HttpOnly";
}

And the usage:

response.setHeader("SET-COOKIE", getHttpOnlyCookieHeader(myOriginalCookie));
user3910752

This code works without using response.setHeader():

public void addCookie(String cookieName, String cookieValue, Integer maxAge, HttpServletResponse response) {  
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setPath("; HttpOnly;");
    cookie.setSecure(isSecureCookie);
    cookie.setMaxAge(maxAge);
    response.addCookie(cookie);
}
shrikant

If you don't want to use:

response.addHeader("Set-Cookie","name=value; HttpOnly");

then you can use the below code in servlet 2.5. It will work perfect in chrome, firefox and IE11 .

Cookie cookie = new Cookie(cookieName, cookieValue);

cookie.setPath(";Path=/;HttpOnly;");
cookie.setSecure(isSecureCookie);
cookie.setMaxAge(maxAge);

response.addCookie(cookie);

Note : As you know that we don't have setHttpOnly() method in servlet 2.5 version, so instead of this you can use:

setPath(";Path=/;HttpOnly;");

it will create a cookie with the path "/" and make the Cookie as HttpOnly

For Java Enterprise Edition versions prior to JEE 6, say Servlet 2.5, you could find a workaround from here at OWASP. Below is an example:

    /**
     * Issue a cookie to the browser
     * 
     * @param response
     * @param cookieName
     * @param cookieValue
     * @param cookiePath
     * @param maxAgeInSeconds
     */
    public static void issueCookieHttpOnly(HttpServletResponse response, 
            String cookieName, 
            String cookieValue, 
            String cookiePath, 
            long maxAgeInSeconds) {

        Date expireDate= new Date();
        expireDate.setTime (expireDate.getTime() + (1000 * maxAgeInSeconds));
        // The following pattern does not work for IE.
        // DateFormat df = new SimpleDateFormat("dd MMM yyyy kk:mm:ss z");

        // This pattern works for Firefox, Chrome, Safari and Opera, as well as IE.
        DateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy kk:mm:ss z");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        String cookieExpire = df.format(expireDate);

        StringBuilder sb = new StringBuilder(cookieName);
        sb.append("=");
        sb.append(cookieValue);
        sb.append(";expires=");
        sb.append(cookieExpire);
        sb.append(";path=");
        sb.append(cookiePath);
        sb.append(";HttpOnly");

        response.setHeader("SET-COOKIE", sb.toString());
    }

For Servlet API 2.5, you can use

response.addHeader("Set-Cookie","name=value; HttpOnly");

Be careful with the use of response.setHeader() because it deletes all the other cookies, for example, the JSESSIONID cookie.

If you don't want to hardcode HttpOnly; or don't like to add header, use apache shiro like this:

void addCookie(javax.servlet.http.Cookie httpCookie,
               HttpServletRequest request,
               HttpServletResponse response) {
    org.apache.shiro.web.servlet.Cookie cookie =
                 new org.apache.shiro.web.servlet.SimpleCookie(httpCookie.getName());

    cookie.setValue(httpCookie.getValue());
    cookie.setPath(httpCookie.getPath());
    // set other stuff from the original httpCookie
    cookie.setHttpOnly(true);

    cookie.saveTo(request, response);
}

Spring does this using reflection without breaking on servlet 2.5 containers.

Method setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class);
if (setHttpOnlyMethod != null) {
    ReflectionUtils.invokeMethod(setHttpOnlyMethod, cookie, Boolean.TRUE);      
}

However setHttpOnly method is only available on Servlet 3.0 onward only.

Cookie cookie = new Cookie("JSESSIONID", session.getId());
cookie.setPath("/");
cookie.setMaxAge(-1);
response.addCookie(cookie);

Actually in my case, this code not work exactly.
Path value are not "/"

But add this cookie.setComment("; HttpOnly;"); works fine!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!