Get Plug.Conn.AlreadySentError when using basic_auth

Hi,

I’m trying to create an simple plug app (with supervisor flag) to test basic_auth.
However, the result always gets returned even if there is an exception Plug.Conn.AlreadySentError.

Have anybody ever seen it and how can I resolve it?

PS: Is there an alternative basic authentication package rather than basic_auth? Which one should I use?

Thank you very much in advance.

my_app.ex

defmodule MyApp do
  use Application

  # See http://elixir-lang.org/docs/stable/elixir/Application.html
  # for more information on OTP Applications
  def start(_type, _args) do
    import Supervisor.Spec, warn: false

    # Define workers and child supervisors to be supervised
    children = [
      # Starts a worker by calling: MyApp.Worker.start_link(arg1, arg2, arg3)
      # worker(MyApp.Worker, [arg1, arg2, arg3]),
      worker(MyRouter, [])
    ]

    # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

my_router.ex

defmodule MyRouter do
  import Plug.Conn
  use Plug.Router

  plug :match
  plug :dispatch
  plug BasicAuth, realm: "Admin Area", username: "admin", password: "secret"

  def start_link do
    Plug.Adapters.Cowboy.http(__MODULE__, [])
  end

  # GET /
  get "/" do
    {:ok, json} = Poison.encode(%{data: "hello world"})

    conn
    |> put_resp_content_type("application/json")
    |> send_resp(200, json)
  end

  match _ do
    send_resp(conn, 404, "Not Found")
  end
end
1 Like

You have your auth plug after your plug match / dispatch. The match / dispatch plugs are what causes the get "/" to run, where you send a 200.

1 Like

Thank you very much Ben.

1 Like