create_session 没有设置 SET-COOKIE header

create_session doesn't set SET-COOKIE header

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

  # 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

returns

[{"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)

returns the user as expected

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

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