使用 Phoenix/Elixir 在本地设置 SSL 时出现问题

Problems setting up SSL locally with Phoenix/Elixir

我在 OSX 上创建了一个新的 Phoenix Web 应用程序,我正在尝试让 SSL 在本地主机上运行。为此,我阅读并执行了 this article. So now I have a server.key, server.crt and server.csr files. The files are not binary and are in readable form. I placed those files in the priv folder as the Phoenix docs suggested.

的步骤

我的配置文件如下所示:

  config :{{name}}, {{name}}.Endpoint,
  http: [port: 4000],
  debug_errors: true,
  code_reloader: true,
  cache_static_lookup: false,
  check_origin: false,
  watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin"]],
  https: [port: 4043,
          otp_app: :{{name}},
          keyfile: System.get_env("server.key"),
          certfile: System.get_env("server.crt"),
          # OPTIONAL Key for intermediate certificates
          # cacertfile: System.get_env("INTERMEDIATE_CERTFILE_PATH")
        ]

当我 运行 mix phoenix.server 时,出现以下错误:

** (Mix) Could not start application {{name}}: {{name}}.start(:normal, []) returned an error: shutdown: failed to start child: {{name}}.Endpoint
    ** (EXIT) shutdown: failed to start child: Phoenix.Endpoint.Server
        ** (EXIT) shutdown: failed to start child: {:ranch_listener_sup, {{name}}.Endpoint.HTTPS}
            ** (EXIT) shutdown: failed to start child: :ranch_acceptors_sup
                ** (EXIT) an exception was raised:
                    ** (MatchError) no match of right hand side value: {:error, {:options, {:certfile, nil}}}
                        (ranch) src/ranch_acceptors_sup.erl:30: :ranch_acceptors_sup.init/1
                        (stdlib) supervisor.erl:243: :supervisor.init/1
                        (stdlib) gen_server.erl:306: :gen_server.init_it/6
                        (stdlib) proc_lib.erl:237: :proc_lib.init_p_do_apply/3

我做错了什么?我是 Phoenix 新手,我正在从事的项目需要在本地主机上使用 SSL 以防止跨域问题。

看来 phoenix 无法找到您的证书。 为了克服这个问题,您可以提供一个 绝对路径 或者可以利用 otp_app 来使用 phoenix 可以使用的相对路径搜索证书。如果您提供 otp_appphoenix 将在您的应用程序根目录中查找证书。

如果你想提供一个绝对路径,你可以这样做:

    keyfile: Path.expand("../../../some/path/to/ssl/cer.key", __DIR__),
    certfile: Path.expand("../../../some/path/to/ssl/cer.crt", __DIR__)

如果你想利用 otp_app,创建两个环境变量,比如 KEY_HOME 和 CERT_HOME。转到控制台并触发这两个命令。您应该稍后将它们添加到您的 bashrc 文件中。

export KEY_HOME=priv/ssl/server.key
export CERT_HOME=priv/ssl/server.crt

您必须在此处包含 priv 目录

现在您的配置如下所示

  https: [port: 443,
  otp_app: :hello_phoenix,
  keyfile: System.get_env("KEY_HOME"),
  certfile: System.get_env("CERT_HOME") 
  ]

不要忘记在 priv/ssl 中复制文件。