I wanted to introduce Basic authentication in a production environment. I've done AWS but never Heroku, so I'd like to mention what I did this time.
Basic authentication is one of the simple ways to restrict access to websites. Basic authentication is one of the functions that comes with the Web server, and you can easily restrict access by just writing a few lines in the file. Basic authentication is one of the authentication methods that can restrict access to a specific area of a website, that is, pages and files. With basic authentication, when you try to access an authenticated website, an authentication dialog like the one in the image above will appear, prompting you to enter your user name (ID) and password.
Added code to application_controller.rb to perform Basic authentication on all controllers. Rails provides the following methods for basic authentication. 「authenticate_or_request_with_http_basic」 This is a method that makes it easy to implement Basic authentication in Rails.
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :basic_auth, if: :production?
private
def production? #← Distinguish between production environment and local.
Rails.env.production?
end
def basic_auth
authenticate_or_request_with_http_basic do |username, password|
username == ENV['BASIC_AUTH_USER'] && password == ENV['BASIC_AUTH_PASSWORD']
end
end
end
Terminal.
% vim ~/.bash_profile
#Press "i" to go to insert mode
#Add the USER and PASSWORD set by yourself as follows.
export BASIC_AUTH_USER='USER'
export BASIC_AUTH_PASSWORD='PASSWORD'
#Press the esc key and:Press wq to save
% sudo vim /etc/environment
Password: #← Password for your PC
#Press "i" to go to insert mode
#Add the USER and PASSWORD set by yourself as follows.
BASIC_AUTH_USER='USER'
BASIC_AUTH_PASSWORD='PASSWORD'
#Press the esc key and:Press wq to save
#Check if it is reflected on Heroku with heroku config.
% heroku config
===App name Config Vars
BASIC_AUTH_USER: 'USER'
BASIC_AUTH_PASSWORD: 'PASSWORD'
username == ENV ['BASIC_AUTH_USER'] && password == ENV ['BASIC_AUTH_PASSWORD'] is an environment variable because if you commit up to Github without making it an environment variable, you can see the password at a glance.
I was able to set up Basic authentication using the above method.
Recommended Posts