Remove Cookie issue - gwt

I have a cookie save a token when a user logs into www.example.com and then it redirects them to example.com/desktop or example.com/mobile depending on what device they're using. When they log out of the desktop app I replace the cookie with null and then call remove cookie in GWT and redirect them to www.example.com, but the cookie still exists. Am I doing something wrong here? I haven't worked with cookies much before so I'm a bit new to this.

Because the cookie was set at another path, you have to use Cookies.removeCookie("cookieName", "/") (/ being the path used in your example) and not Cookies.removeCookie("cookieName").
This is because without a specified path, the path defaults to the one of the current page (see document.cookie).
So, you're trying to remove the cookie at path=/desktop, whereas it's actually at path=/, so the removal fails.
Remember that you could have two cookies with the same name but different paths; so you could have a cookieName at path=/ and a _cookieName at path=/desktop. Removing the cookie at path=/ won't remove the one at path=/desktop, and conversely, removing the one at path=/desktop won't remove the one at path=/.
As a side note: when accessing /desktop, the browser would send both cookies, which could have different values.
In brief, because you set your cookie at /, remember to always pass / as the path, everywhere, or you could create a new cookie rather than modifying the existing one, or fail to remove it (which you're experiencing right now).
See also Cookies.removeCookie(String,String)

In case you also need a non-default domain use
public static native void removeCookie(String name, String path, String domain) /*-{
$doc.cookie = name + "=" + ((path) ? ";path=" + path : "")
+ ((domain) ? ";domain=" + domain : "")
+ ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
}-*/;

Related

How to specify the domain of cookie with Scala and Play

I want cookies which is set from test.domain.com to be set for .domain.com so that that it can still be used from anothertest.domain.com. Basically cookies should be shared between subdomains.
I called backend deployed at test.domain.com and set cookies with OK response as follows:
Ok("some response").withCookies(Cookie("id", id), Cookie("token", token))
And in application.conf I have set the session domain to ".domain.com"-
session {
\#Sets the cookie to be sent only over HTTPS.
\#secure = true
\#Sets the cookie to be accessed only by the server.
\#httpOnly = true
\#Sets the max-age field of the cookie to 5 minutes.
\#NOTE: this only sets when the browser will discard the cookie. Play will consider any
\#cookie value with a valid signature to be a valid session forever. To implement a server side session timeout,
\#you need to put a timestamp in the session and check it at regular intervals to possibly expire it.
\#maxAge = 300
\#Sets the domain on the session cookie.
domain = ".domain.com"
}
However, the cookie is being set for test.domain.com rather than .domain.com.
I want to use this cookie with anothertest.domain.com .
Can you please help me with this.
You don't have to change the configuration, you can add all attributes of a cookie when creating it.
Cookie("bla", bla).withDomain(xxx)
// Or
Cookie("bla", bla, domain = XXX)
(Not sure of exact name, I don't have documentation with me right now)

Authentication That Doesn't Require Javascript?

I have a Web API app, initialized thusly:
app.UseCookieAuthentication();
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseOAuthBearerTokens(OAuthOptions);
app.UseGoogleAuthentication();
For calls to most controllers, it works great. However, it also requires a bit of javascript before client-side service calls are made:
function getSecurityHeaders() {
var accessToken = sessionStorage["accessToken"] || localStorage["accessToken"];
if (accessToken) {
return { "Authorization": "Bearer " + accessToken };
}
return {};
}
The problem is that we have a certain type of controller (one that accesses files) where no javascript can be run during the call. For example, the call might be to:
http://mysite/mycontroller/file/filename.jpg
...where the value is assigned as the src attribute of an img tag. The call works, but Thread.CurrentPrincipal.Identity is unauthenticated with a null name, so there's currently not a way to enforce security.
I'm new to Web API, so it may be a dumb question, but what's the way around this? What switches do I need to flip to not require javascript to add security headers? I was considering trying to find a way to force an authorization header in an IAuthorizationFilter or something, but I'm not even sure that would work.
So I figured out the solution to my problem.
First, I needed to configure the app to use an authentication type of external cookies thusly:
//the line below is the one I needed to change
app.UseCookieAuthentication(AuthenticationType = DefaultAuthenticationTypes.ExternalCookie);
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseOAuthBearerTokens(OAuthOptions);
app.UseGoogleAuthentication();
Second, it turned out there was a line of code in my WebApiConfig file that was disabling reading the external cookie:
//this line needed to be removed
//config.SuppressDefaultHostAuthentication();
After that, I could see the external cookie from Google, which passed along an email address I could identify the user with.

Why there is an existing default cookie name in Cookie in GWT?

I just found out that there is an existing default cookie name in Cookie before i actually adds my cookie name into it. That default cookie is JSESSIONID.
Collection<String> cookies = Cookies.getCookieNames();
for (String cookie : cookies) {
String cookieValue = Cookies.getCookie(cookie);
String[] itemMeaningIDcompanyMeaningID=cookie.split("_");
}
If i live the default cookie there, then i have a problem cos I need to convert cookie name into array so i may split the default cookie & that could cause runtime error.
i suspect that the default cookie is used for something else in GWT, so if i remove it then the system may not run properly.
So my question is, should i remove that default cookie or i just leave it there?
JSESSIONID is a cookie generated by the servlet container (like Tomcat or Jetty) and used for session management. You should leave it there unless you don't use sessions and don't plan to use them ever (which is rarely the case for any non trivial webapp).

Setting Object as cookie in servlet

i am using cookie to avoid rpc call i am using cookie for user authentication for the first time (when he logs in ).For that i am unable to set an User object in the servlet as cookie .because cookie constructer allows on only string as value .
How can i set object as cookie ?
other than cookie is there any way to get the object fron HTTP session without making an RPC call ?
I assume you have some system for translating objects to and from JSONs. So simply translate the object into a JSON string, save it to the cookie, and translate it back into an object when you extract it from the cookie. I recommend the piriti library for handling JSONs (GWT comes with its own JSON handling library built in, but it has some limitations).
if(authenticated){
LoginPojo ch=new LoginPojo();
ch.setImage("image");
ch.setFullName( u.getFirst_name()+" "+u.getLast_name());
ch.setLogin(u.getLogin);
ObjectMapper objectMapper=new ObjectMapper();
String jsonInString = objectMapper.writeValueAsString(ch);
Cookie c=new Cookie("VISITOR",jsonInString);
// c.setSecure(true);
response.addCookie(c);
request.getRequestDispatcher(rootURL).forward(request, response);
}
But somebody says : "The HTTP State Management Mechanism specification (which deals with Cookies) states that you can't have the double quote character in the value of the cookie unless it wraps the entire thing.
Don't (try to) put JSON in cookies."

Add Page Tab redirect to invalid location

When I've user Add Page Tab Dialog, I've passed redirect_uri like this
http://MYSITE/?r=c/action&token=123456789
when the dialog come back, it strips the token variable, so the url looks like
http://MYSITE/?r=c%2Faction&&tabs_added%5B176281002470701%5D=1#_=_
the token variable lost,
any body have any idea why this happen?
Might be a bug or the forward-slash. Try adding an extra param at the end that you don't care about or removing the forward-slash
http://MYSITE/?r=c/action&token=123456789&t=1
http://MYSITE/?r=caction&token=123456789
One option is to put all your needed variables in a single base64 string and pass that guy over as your single querystring parameter.
Pseudo-code would be:
data = toBase64String("action&token=123456789")
redirect_uri = "http://MYSITE/?data=" + data;
Then you decode it wherever you redirect to.