Play: Session Cookie not set. Cannot read Cookie u

2019-08-12 01:13发布

问题:

In order to send an authorization token (that should be stored in a database) to my server, I do an AJAX call in my .scala.html file.

$.ajax({
       url: "http://localhost:9000/storeauthcode",
       type: 'get',
       data: {code: authResult['code']},
       contentType: 'application/json',
       dataType: 'json',
       success: function(result) {
       // Handle or verify the server response.
           console.log("you're fully logged in now.")
           console.log(JSON.stringify(result, null, 2))
           console.log("document.cookie = "+document.cookie)
       },
       error: function (xhr, status, error) {
           console.log("error\n")
           console.log(xhr.responseText)
       }

   });
  }

On the server side, I store the auth code and return a json response

  def storeAuthCode  = Action { request =>
  //store credentials in database
  //...
  //return some data
  Ok(Json.toJson(Map("a"->"b"))).withSession("code"-> "someAuthCode", "id"->"someId")
}

If I try to print all cookies in the success handler of my AJAX call via

console.log("document.cookie = "+document.cookie)

document.cookie seems to be empty although the server should have created a session Cookie (or at least anything). document.cookie should return a ";" separated list of my Cookie values.

How can I set my Cookies successfully?

回答1:

The reason why you can't read this is HTTPOnly flag set for Play's session cookie.

You have several options which you can use instead:

  1. Send code and id in the JSON object (like "a"->"b")
  2. You can also send them as response headers so you can get them within your success callback like:

    Ok(Json.toJson(Map("a" -> "b")))
      .withHeaders(
        "code" -> "foo",
        "id" -> "bar"
      )
      .withCookies(
        Cookie("code", "foo"),
        Cookie("id", "bar")
      )
    

    jQuery

    success: function(data, textStatus, jqXHR) {
        console.log(jqXHR.getResponseHeader('code'));
        console.log(jqXHR.getResponseHeader('id'));
    },