Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a cookie after response.sendRedirect()?

I'm redirecting the user to some URL and I want to send a cookie with it:

        Cookie cookie = new Cookie("CADASTROADM", "someValue");
        cookie.setPath("/");
        cookie.setMaxAge(129600); //With it or without, makes no difference.
        URL urlToRedirect = new URL(pageToRedirect);
        cookie.setDomain(urlToRedirect.getHost());//With it or without, makes no difference.
        response.addCookie(cookie);
        response.sendRedirect(pageToRedirect);

However, when he's redirected to the page, the cookie is not there. I cannot use requestDispatcher.forward() because I'm redirecting the user to an absolute page.

Is it possible? What am I doing wrong?

like image 747
thevoyager Avatar asked Aug 08 '12 20:08

thevoyager


1 Answers

Cookies can only be set/retrieved for the same domain or a subdomain as where the request is been sent to. Otherwise it's a huge security hole.

So, if you're redirecting to a different domain, then the cookie will not be available over there. If you're explicitly setting the cookie domain to that different domain, then it will be plain ignored. If you're not explicitly setting the cookie domain (and it thus defaults to the same domain as where the request is been sent to), then it would only be available for the current domain, not for the redirected domain.

You need to look for alternate ways, depending on the concrete functional requirement. It's hard to suggest one as you didn't tell anything about the concrete functional requirement in your question at all. Perhaps you should just send some specific request parameter along?

like image 155
BalusC Avatar answered Nov 15 '22 03:11

BalusC