【问题标题】:create_session doesn't set SET-COOKIE headercreate_session 未设置 SET-COOKIE 标头
【发布时间】:2017-07-08 15:52:25
【问题描述】:

我假设 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)

按预期返回用户

【问题讨论】:

  • create_session 在哪里定义?它必须返回一个 conn,在这种情况下您应该将其分配回 (conn = case find_user(...) do ... end),因为 Elixir 结构是不可变的。
  • 发送给浏览器的实际响应中是否存在cookie? Plug.Session 在实际发送响应之前设置实际会话 cookie(使用 register_before_send),因此它不会出现在 conn.resp_headers 中,但如果您发出真正的请求,它应该在那里。
  • 好吧,我想通了,我看不到 cookie,因为它是 httpOnly:true 感谢您的帮助。你想用所有这些信息做一个答案并将其标记为已回答:)

标签: session-cookies phoenix-framework setcookie


【解决方案1】:

您在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

【讨论】:

  • 并且默认情况下,phoenix 添加了httpOnly: true 标志,因此您不会在 document.cookies 中看到它
猜你喜欢
  • 1970-01-01
  • 2020-08-16
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
  • 1970-01-01
  • 2022-10-05
  • 2022-01-23
相关资源
最近更新 更多