koukiblog

たぶんweb系の話題

PhoenixでHTTP Headerを利用した認証を行う

PhoenixAPIを実装するときに、http headerを利用して簡易な認証を行う時の方法。
http headerで認証を行うplugを作成します。

/web/plugs/api_auth.ex

defmodule App.Plug.APIAuth do
  import Plug.Conn

  def init(default), do: default

  def call(conn, auth_header) do
    {key, value} = auth_header
    header = Enum.find(conn.req_headers, &elem(&1, 0) == key)

    if header && elem(header, 1) == value do
        conn
      else
        send400 conn
    end
  end

  defp send400(conn) do
    conn
    |> put_resp_content_type("text/plain")
    |> send_resp(400, "Bad Request")
    |> halt
  end
end

Phoenixの場合、http headerはconn.req_headersで取得できるのでそれを利用します。
{key,value}のtupleのリストになっています。
Plug.Conn – Plug v1.1.6

作成したPlugをRouterに設定すれば完了です。

web/router.ex

  pipeline :api do
    plug :accepts, ["json"]
    plug App.Plug.APIAuth, {"x-sample-key", "xxxxx"}
  end

環境毎に変更する場合は、configに追記して、Application.get_env で取得すればok