如何在Phoenix应用程序中设置conn.secret_key_base

And*_*rie 5 elixir phoenix-framework

我在Phoenix应用程序中收到以下错误:

cookie store expects conn.secret_key_base to be set

它似乎来自|> redirect(to: session_path(conn, :new))我的PostController模块中的这个验证函数的行:

  defp authenticate(conn, _opts) do
    if conn.assigns.current_user do
      conn
    else
      conn
      |> put_flash(:error, "You must be signed in to post a project.")
      |> redirect(to: session_path(conn, :new))
      |> halt()
    end
  end  
Run Code Online (Sandbox Code Playgroud)

显然,这个错误意味着需要设置conn.secret_key_base.

我在哪里以及如何设置此值?

Gaz*_*ler 13

创建凤凰应用程序时,应默认指定:

https://github.com/phoenixframework/phoenix/blob/2861f0db3df3d81ee6ce79f928ef4e0b439c4dcd/installer/templates/new/config/config.exs#L16
Run Code Online (Sandbox Code Playgroud)

如果您缺少此配置,请将以下内容放入config/config.exs:

config :my_app, MyApp.Endpoint,
  secret_key_base: "some_secret",
Run Code Online (Sandbox Code Playgroud)

您可以使用mix phoenix.gen.secret任务生成应该使用的值,而不是"some_secret".

  • “不推荐使用 mix phoenix.gen.secret。改用 phx.gen.secret。” - 对于像我这样的其他谷歌员工。 (2认同)