Search code examples
ruby-on-rails-4http-authentication

Is there any way to encrypt the Http basic authentication password in rails?


I have written the following in my controller:

http_basic_authenticate_with name: "foo", password: "bar", except: [:new, :show, :edit, :create]

but when I push it to my repo, the password is there for everyone to see. Is there any way to encrypt the password?


Solution

  • You probably want to use environment-variables for this :) There's a gem (Like for everything basically): https://github.com/bkeepers/dotenv

    In your .env file you'd have the following:

    AUTHENTICATION_USERNAME="foo"
    AUTHENTICATION_PASSWORD="bar"
    

    Where as in your controller you write it like so:

    http_basic_authenticate_with name: ENV['AUTHENTICATION_USERNAME'], password: ENV['AUTHENTICATION_PASSWORD'], except: [:new, :show, :edit, :create]
    

    This way your code is completely separated from the actual information. Make sure to not add the .env-file to your git-repository by adding this to your gitignore:

    .env
    

    So what this does is it'll load these variables you set up in .env into your existing environment variables. This way somebody needs to actually log into your server and get access to that particular file in order to get the username/password. And this should be more secure than having the username/password in plain text inside your controller ;)