Search code examples
oauthelixirphoenix-frameworkueberauth

Elixir Phoenix setting and using environment variables


I have a phoenix app that is making an OAuth call to github. I want to store my secret keys as environment variables so I can keep them out of version control.

I have created a file called .env where I define my private key:

export GITHUB_CLIENT_ID="891538_my_key_bf0055"

I attempt to obtain my private key in my config.exs file, the file responsible for configuring your application using System.Config.

config :ueberauth, Ueberauth.Strategy.Github.OAuth, client_id: System.get_env("GITHUB_CLIENT_ID"), client_secret: System.get_env("GITHUB_SECRET_ID")

To make a long story short, my controller is almost able to handshake with github for the request. When I make a request to github to authorize my app, http://localhost:4000/auth/github, I can almost make a request and I see a 404 page from github. I have noticed that the url has no client_id though!

My router to access the callback is

  scope "/auth", Discuss do
    pipe_through :browser # Use the default browser stack

    # make request to github, google, fb
    get "/:provider", AuthController, :request
    get "/:provider/callback", AuthController, :callback
  end

And what I get is URL with no value https://github.com/login/oauth/authorize?client_id=&redirect_uri=http%3A%2F%2Flocalhost%3A4000%2Fauth%2Fgithub%2Fcallback&response_type=code&scope=user%2Cpublic_repo`

If I don't use an environment variable in config.exs and instead use the string value, the request work as it should.

How do I use environment variables in Phoenix?


Solution

  • If using Distillery releases, you may want to avoid using System.get_env/1 from inside the config.exs files, as it will store the value of the environment variable at build time, rather than runtime.

    In the prod.exs configuration, you can use

    config :ueberauth, Ueberauth.Strategy.Github.OAuth,
        client_id: "${GITHUB_CLIENT_ID}",
        client_secret: "${GITHUB_SECRET_ID}"
    

    Then generate the release with REPLACE_OS_VARS=true environment variable set.

    Distillery Docs