Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an httponly cookie with javax.servlet 2.5

Tags:

here is a function that sets a cookie:

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

I believe in servlet 3.0, there is a way to do this directly. Unfortunately my organization uses 2.5 and UPGRADING at this juncture IS NOT AN OPTION.

is there way to use the response to set the cookie? Here's an example i found online

response.setHeader("SET-COOKIE", "[SOME STUFF]" +"; HttpOnly") 

If this is the only way to do what i want, what would i replace "[SOME STUFF]" with so that i don't lose any of the data that my function currently stores in the cookie?

like image 616
aamiri Avatar asked Oct 30 '12 20:10

aamiri


People also ask

How do I set my cookie to HttpOnly?

Set HttpOnly cookie in PHPini_set("session. cookie_httponly", True); This is the most common way to set cookies in PHP, empty variables will hold their default value.

Can I set HttpOnly cookie from browser?

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly .

What is HttpOnly cookie in Java?

Java HttpCookie setHttpOnly() Method The setHttpOnly(Boolean httpOnly) method of Java HttpCookie class is used to indicate whether the cookie can be considered as HTTPOnly or not. If it is set to true then the cookie cannot be accessed by scripting engines like JavaScript.


2 Answers

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)); 
like image 137
Val Avatar answered Sep 27 '22 22:09

Val


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); } 
like image 45
user3910752 Avatar answered Sep 28 '22 00:09

user3910752