【问题标题】:What's the alternative of before_filter from Rails in Phoenix/Elixir?Phoenix/Elixir 中 Rails 的 before_filter 的替代方案是什么?
【发布时间】:2019-01-18 05:57:42
【问题描述】:

在我的 Phoenix 应用程序中,我有一个管道和范围“api”

  pipeline :api do
    plug(:accepts, ["json"])
  end


  scope "/api" .....
    # .....
  end

如何通过通过特殊标头传递的 API 密钥保护它?也就是说,我想要这样的东西:

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

  :before_filter :authenticate_user_by_api_key!


  def authenticate_user_by_api_key!(conn, params) do
    # check if a header exists and key is valid
  end
end

我正计划验证一个标题。 如何在不依赖任何第三方库的情况下做到这一点?

还有。如果我想使用 模块 而不是单个函数,我该怎么做?

【问题讨论】:

标签: rest elixir phoenix-framework


【解决方案1】:

本地插头

如果是本地方法,您可以简单地在控制器中使用plug 构造。

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

  plug :authenticate_user_by_api_key!


  defp authenticate_user_by_api_key!(conn, params) do
    # Authenticate or something
  end
end

See this answer 并阅读有关Plugs here 的更多信息。


模块插头

如果您想从模块调用函数,您的模块必须导出 init/1call/2 方法:

defmodule MyApp.Plugs.Authentication do
  import Plug.Conn

  def init(default), do: default

  def call(conn, default) do
    # Check header for API Key
  end
end

并在您的控制器中像这样使用它:

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

  plug MyApp.Plugs.Authentication

  # Controller Methods
end

阅读Phoenix Guide on Module Plugs了解更多详情。

【讨论】:

  • 谢谢。如果我想使用模块而不是单个函数,我该怎么做?
  • @Meji 更新了答案
  • 这不是答案。 MyApp.Plugs.Authentication 应该是什么样的?它必须具备哪些功能?会调用什么函数?
  • 或许是我没注意到
猜你喜欢
  • 1970-01-01
  • 2012-02-07
  • 2021-11-13
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多