create_session未设置SET-COOKIE标头

时间:2017-02-19 11:02:43

标签: session-cookies phoenix-framework setcookie

我假设create_session如果endpoint.ex配置为使用cookie存储,则设置SET-COOKIE响应头

  # The session will be stored in the cookie and signed,
  # this means its contents can be read but not tampered with.
  # Set :encryption_salt if you would also like to encrypt it.
  plug Plug.Session,
    log: :debug,
    store: :cookie,
    key: "some_key",
    signing_salt: "some_salt"

这是我的身份验证控制器(只是其中的一部分)

  def callback(%{ assigns: %{ ueberauth_auth: auth } } = conn, params) do
    params = build_params(auth)
    user = find_or_create_user params
    conn = put_session(conn, :current_user, user)
    IO.inspect conn.resp_headers
    IO.inspect get_session(conn, :current_user)
    render conn, "index.html"
    #Helpers.redirect!(conn, "/")
  end

  def build_params(auth) do
    %{email: auth.info.email, github_token: auth.credentials.token, github_user: auth.info.nickname}
  end

  def find_or_create_user(params) do
    case DBRepo.get_by(User, email: params.email) do
        nil ->
          User.changeset(%User{}, params)
          |> DBRepo.insert
        results ->
          results
    end
  end
  

IO.inspect conn.resp_headers

返回

[{"cache-control", "max-age=0, private, must-revalidate"},  {"x-request-id", "vh8l2deodne1k2iloa4c3e4qdpmh857n"},  {"x-frame-options", "SAMEORIGIN"}, {"x-xss-protection", "1; mode=block"},  {"x-content-type-options", "nosniff"}]
IO.inspect get_session(conn, :current_user)
     

按预期返回用户

1 个答案:

答案 0 :(得分:2)

您在resp_headers中未看到会话Cookie,因为Plug.Session设置了该Cookie just before the response is actually sent, using Plug.Conn.register_before_send。如果您使用任何HTTP客户端(浏览器,curl等)发出请求,您将看到Set-Cookie标题。

defmodule MyApp.PageController do
  use MyApp.Web, :controller

  def index(conn, _params) do
    conn
    |> put_session(:foo, :bar)
    |> text("")
  end
end
$ curl -I localhost:4000
HTTP/1.1 200 OK
server: Cowboy
date: Mon, 20 Feb 2017 08:57:36 GMT
content-length: 0
set-cookie: _my_app_key=SFMyNTY.g3QAAAABbQAAAANmb29kAANiYXI.F0G6lsgPxsYjq97tonLy1gRkOBUVcfwqKZdozgGRG-c; path=/; HttpOnly
content-type: text/plain; charset=utf-8
cache-control: max-age=0, private, must-revalidate
x-request-id: uoplksup9ndakf5sdr5shpjsjhvu849v
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
x-content-type-options: nosniff