DEV Community

loading...

How to secure your private keys.

terrythreatt profile image Terry Threatt ・2 min read

Security is key

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.

Let's get started:

Let's create a Rails application.

$ rails new blog
Enter fullscreen mode Exit fullscreen mode

This command requires Ruby on Rails to be installed. Click here for installation

Let's navigate to our new app and generate some models, controllers, and views.

$ cd blog
$ rails generate scaffold post title:string body:text
$ rails generate scaffold comment post_id:integer body:text
$ rake db:migrate
Enter fullscreen mode Exit fullscreen mode

Let's add a few gems.

// file: blog/Gemfile
// Add these into the file

...
gem 'dotenv-rails', groups: [:development, :test]
gem 'omniauth-google-oauth2'
...
Enter fullscreen mode Exit fullscreen mode

dotenv - Popular gem that allows you to hide your private keys.
omniauth - Gem that allows you to create authentication in your app.

Click here to get API keys

Execute gem installation

$ bundle 
$ rails server
Enter fullscreen mode Exit fullscreen mode

Configure omniauth

// 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
Enter fullscreen mode Exit fullscreen mode

Notice provider :google_oauth2, '123456789', 'Your_Client_Secret'. This is where you can put your secret keys but they wouldn't be very secret here.

Configure omniauth

// Create this file => blog/.env 
// Add your secret credentials 

GOOGLE_CLIENT_ID = '123456789'
GOOGLE_CLIENT_SECRET = 'Your_Client_Secret'
Enter fullscreen mode Exit fullscreen mode

Update omniauth

// replace you secret keys 

provider :google_oauth2, ENV[GOOGLE_CLIENT_ID], ENV[GOOGLE_CLIENT_SECRET]
Enter fullscreen mode Exit fullscreen mode

Prepending ENV will give you access to the environment key we created for your secret credentials in the .env file.

Hide your secret file

// Locate your gitignore file => blog/.gitignore
// Add this snippet

# This hides your file from being uploaded to your repository
  .env 
Enter fullscreen mode Exit fullscreen mode

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.

Terry Threatt

Discussion (0)

pic
Editor guide