Max
Max

Reputation: 661

Play framework, how do you access cookie in client side(javascript)?

I'm trying to implement https://github.com/jamesward/play-rest-security for my REST endpoint.

I set the returning result of my implementation with Scala Play result.withCookies(Cookie(AUTH_TOKEN, authToken)).

But, in the client side(js), somehow when i try to access using document.cookie. The cookie is not found.

With using the Java API of response().setCookie(AUTH_TOKEN, authToken) seems different though. Its accessible via document.cookie.

What am i missing here?

Upvotes: 1

Views: 2373

Answers (3)

Federico
Federico

Reputation: 3920

This worked for me in Play 2.5.x, where the other answers involving application.conf didn't.

Cookie(AUTH_TOKEN, authToken, httpOnly = false)

This might be because application.sesssion only deals with sesssion cookies. For internationalization cookies, for example, you have to modify play.i18n.langCookieHttpOnly, and so on.

The aforementioned solution, on the other hand, deals with cookies individually.

Upvotes: 0

Kris
Kris

Reputation: 4823

It might be that httpOnly is set to true (it's so by default) in your application.conf. This means that you can't read your cookies in your JavaScript on the client side. Put session.httpOnly=false in your application.conf.

But consider the security implications.

Upvotes: 3

jsonmurphy
jsonmurphy

Reputation: 1600

Play sets the HttpOnly flag on its cookies by default, so they wont be accessible via clientside code (js). From Google:

HttpOnly is an additional flag included in a Set-Cookie HTTP response header. Using the HttpOnly flag when generating a cookie helps mitigate the risk of client side script accessing the protected cookie (if the browser supports it).

See here for a possible way to turn this off. Particualarly:

So, it Play 1 you can set application.session.httpOnly=false but in Play 2.1 they changed to session.httpOnly=false

Those should be set in your application.conf i believe. Hope that helps.

Upvotes: 1

Related Questions