How to introduce Basic authentication

【Overview】

1. Conclusion </ b>

2. What is Basic authentication? </ B>

3. How to introduce Basic authentication </ b>

4. Development environment </ b>

  1. Conclusion

Set the environment variable with the authenticate_or_request_with_http_basic method, set it with vim ~ / .zshrc, and then set the environment variable again in the terminal </ b>!


2. What is Basic authentication?

This is user authentication (enter ID and password), which is the original HTTP communication standard. Once deployed, everyone can see it, so only those who know the username / password can see it!
3. How to introduce Basic authentication

❶ Use the authenticate_or_request_with_http_basic method (which is a Rails method) and set the username / password. I try to do it in advance with before_action. Since it is an environment variable, "@@@@" "~~~~" (divided into @@@@ and ~~~~ to avoid the meaning of the same name) is not the contents of the user name / password but the contents. Give it a name to put it in. If you want to check the operation, enter your favorite number characters in the "@@@@" part instead of the name, and it will be reflected immediately when you do rails s!

app/controller/application_controller



before_action:basic
  def basic
    authenticate_or_request_with_http_basic do |username, password|
    username == ENV["@@@@"] && password == ENV["~~~~"]
    end
  end

❷ After entering "vim ~ / .zshrc" in the terminal, enter the contents of the user name / password based on the name given in ❶. If you write the contents in ❶, the user name / password will be exposed on Github, so you will be disclosing the password to someone who has this knowledge. "****" and "XXXX" are separated for convenience not to be combined.

#For macOS Catalina

$ vim ~/.zshrc
#Press "i" in half-width alphanumeric characters to enter insert mode

$ export @@@@='****' #"@@@@"Is set in ❶"****"Is your favorite username
$ export ~~~~='XXXX' #"@@@@"Is set in ❶"XXXX"Is your favorite password name
#In half-width alphanumeric characters:Press "wq" to finish

$source ~/.zshrc 
#If you do not do this, it will not be reflected.

❸ When deploying, set environment variables at the deployment destination. This time it's Heroku. You can check if it is set in $ heoku config.

% heroku config:set @@@@="****"
% heroku config:set ~~~~="XXXX"
#Completed setting environment variables on heroku

#Then commit to github. Then push it to heroku with a command.
% git push heroku master

  1. Development environment

macOS Catalina 10.15.4 Ruby 2.6.5
Rails 6.0.3.3
Visual Studio Code 1.49.2

Recommended Posts