October 17, 2019
There’s many ways to protect access to your API, but this one is very quick to implement. The idea is to block access to a host(s), unless you send a specific header.
Let’s name this header as “x-let-me-in”
The whole logic can be handled by one function:
defp require_header(conn, _) do if conn.host =~ "samplehost.com" do case(get_req_header(conn, "x-let-me-in")) do [allow_access] when allow_access == "true" -> conn _ -> Logger.info( "A request from " <> to_string(:inet_parse.ntoa(conn.remote_ip)) <> " has no x-let-me-in header" ) conn |> redirect(to: "/") |> halt() end else conn end end
Now create a pipeline for the plug:
pipeline :protect_access do plug :require_header end
and place it somewhere under :browser
pipeline :browser do ... plug :protect_access end
And that’s it! At some point you may want to move host names to config.exs.
You can use a web-proxy to inject the header but I like using browser extensions. The one that works well for me is called “Modify Header Value” (https://mybrowseraddon.com/modify-header-value.html)
Bear in mind, that some servers (like Nginx) may require additional setting to allow custom headers to be passed in.