Security in your application should be a large priority for a developer. Anyone having access to your sensitive information can wreck havoc in your application and possibly your personal information. Even if it is a pet project to learn, It is always good practice to ensure you secure your keys. I will walk through a simple application to demonstrate how to secure your private keys to prevent anyone to publically access your secure information.
$ rails new blog
This command requires Ruby on Rails to be installed. Click here for installation
$ cd blog $ rails generate scaffold post title:string body:text $ rails generate scaffold comment post_id:integer body:text $ rake db:migrate
// file: blog/Gemfile // Add these into the file ... gem 'dotenv-rails', groups: [:development, :test] gem 'omniauth-google-oauth2' ...
dotenv - Popular gem that allows you to hide your private keys.
omniauth - Gem that allows you to create authentication in your app.
$ bundle $ rails server
// Create this file => blog/config/initializers/omniauth.rb // Add this snippet Rails.application.config.middleware.use OmniAuth::Builder do provider :google_oauth2, '123456789', 'Your_Client_Secret' end
provider :google_oauth2, '123456789', 'Your_Client_Secret'. This is where you can put your secret keys but they wouldn't be very secret here.
// Create this file => blog/.env // Add your secret credentials GOOGLE_CLIENT_ID = '123456789' GOOGLE_CLIENT_SECRET = 'Your_Client_Secret'
// replace you secret keys provider :google_oauth2, ENV[GOOGLE_CLIENT_ID], ENV[GOOGLE_CLIENT_SECRET]
Prepending ENV will give you access to the environment key we created for your secret credentials in the .env file.
// Locate your gitignore file => blog/.gitignore // Add this snippet # This hides your file from being uploaded to your repository .env
Now you are able to rest assured your secret API keys are indeed secret and your application still has access when needed. I hope this helps keep your next project secure. If you enjoyed this article please feel free to follow me.