401 Unauthorized when using environment variables in devise omniauth config
Environment
- Ruby '2.6.3'
- Rails '5.2.3'
- Devise 4.6.2
Current behavior
When setting the devise.rb config omniauth solution using ENV variables, I have run into unexpected behavior. Specifically when specifying a scope, like so:
config.omniauth :discord, ENV['id'], ENV['secret'], scope: 'email'
SOME users are unable to be authenticated with this config; returning {"code": 0, "message": "401: Unauthorized"} (https://github.com/adaoraul/omniauth-discord/issues/19) (https://stackoverflow.com/a/21675190/634401).
When hard-coding these values in, rather than using ENV variables, everything works as expected for all users. Also, when no scope is present, using environment variables does work fine.
Hi @tbhockey, thanks for your report.
When hard-coding these values in, rather than using ENV variables, everything works as expected for all users
I don't know how we could be doing something that would cause this. Something that I would try first to use ENV#fetch instead of ENV#[] to fail fast when the variables are not available.
Also, can you tell how you set your environment variables?
@tegon in development i am loading them on boot in application.rb from a local_env.yml file.
config.before_configuration do
env_file = File.join(Rails.root, 'config', 'local_env.yml')
YAML.load(File.open(env_file)).each do |key, value|
ENV[key.to_s] = value
end if File.exists?(env_file)
end
I will try using fetch as you suggest when I have some time. Thank you.
Ok, I'll wait on your response on fetch.
I've never seen this way of loading environment variables, usually, they are set on the server or using a Gem like https://github.com/bkeepers/dotenv
Well on production server (heroku) they are simply added to heroku's env config. And i'm just averse to adding dependencies for simple things :)
@tbhockey were you able to test what happens after using fetch?
@tegon it's been a while now and unfortunately I can't remember exactly what I did to resolve this. But i don't actually think using fetch made any difference. There were issues with the discord-omniauth gem which were preventing this from working properly, and I ended up not using that approach at all. So it's entirely possible this whole issue with the ENV variables, while confusing, was not actually an issue directly after all.
Ok, I'm going to close this then.