Trouble reading env variables on dev machine in basic_auth

Disclaimer: new to Phoenix, my apologies in advance if this a beginner error.

I implemented basic_auth to secure access to app on Heroku while in development. I have been able to get it to work on Heroku using:

config :basic_auth, my_auth_with_system: [
  username: {:system, "BASIC_AUTH_USERNAME"},
  password: {:system, "BASIC_AUTH_PASSWORD"},
  realm:    {:system, "BASIC_AUTH_REALM"}
  ]

I am not able to get this to work on my dev machine. I setup an .env file with

export BASIC_AUTH_USERNAME="admin"
export BASIC_AUTH_PASSWORD="example_password"
export BASIC_AUTH_REALM="realm"

I was able to the variable in iex, but the basic_auth didn’t accept the username and password.

iex(1)> System.get_env("BASIC_AUTH_USERNAME")
"admin"

Are there any special considerations for handling env on a local dev machine? Phoenix 1.3

The code looks valid. What’s the location of config?
Maybe it’s something about config.ex / dev /prod and overriding config keys

I tried including the basic_auth config in both dev.exs and config.exs (not at the same time) without success.

dev.exs
…
config :basic_auth, my_auth_with_system: [
username: {:system, “BASIC_AUTH_USERNAME”},
password: {:system, “BASIC_AUTH_PASSWORD”},
realm: {:system, “BASIC_AUTH_REALM”}
]

config.exs
…

config :basic_auth, my_auth_with_system: [
  username: {:system, "BASIC_AUTH_USERNAME"},
  password: {:system, "BASIC_AUTH_PASSWORD"},
  realm:    {:system, "BASIC_AUTH_REALM"}
  ]

# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"

That whole {:system ENV_VAR_NAME} tuple in config is a hack and the community it moving away from it. It was never a general solution. It was only a format that some libraries would support, for some config keys. And it really messes with performing releases.

I’d recommend you look them up yourself somewhere in your initialization code. One approach is during your Application.start callback to perform System.get_env on those keys and then Application.put_env the results.

4 Likes

The issue is: as far as i remember basic_auth is using macros-in-a-plug and it’ll bake in these values at compile time. Tuple hack allowing to avoid that

Oh! I didn’t realize “basic_auth” was the name of a specific library. I’ll leave my comment as a general statement, but let others try to deal with the specifics of the library. Reading config settings at compile time is exactly the problem I was referring to though.