January 2, 2019
Sometimes we need to keep secrets. For instance, if you want to use
ggmap after July 2018 you need an API key and to provide billing details to Google. You definitely don’t want to accidentally include your personal API key in a blog post.
This blog is generated using the awesome
blogdown package, which means all this wonderful stuff is generated from RMarkdown documents that are available in the Github repository visibledata/visibledata.github.io that powers the website. It’s therefore extremely important I don’t accidentally include the key anywhere in my repository. But I want to consistently use API keys anywhere in the website.
If you want to do something similar, I recommend following these instructions:
- Add the following lines to your
Add these changes to a commit and push these to Github.
Don’t proceed until you’ve done step 2. You need to protect these two files.
You’re going to need to create an SSH key, so either load up the terminal (-nix systems) or Command Prompt (Windows) and run the following code (I chose
blog_vaultas the name for my file).
ssh-keygen -t rsa # Enter file in which to save the key (/Users/charliejhadley/.ssh/id_rsa):
Now we’re going to create the
static/data/secret-keys.R file where we will iteratively add our tokens and other secrets using Gabor Csardi’s awesome
library("secret") library("here") ## ==== Create a vault ## Run these lines ONCE ONLY my_vault <- here("static", "data", "secret-vault.vault") create_vault(my_vault) ## ==== Create a user ## This uses the ssh-key we created above, run this code ONCE ONLY key_dir = "/Users/martinjhnhadley/.ssh" charliejhadley_public_key <- file.path(key_dir, "blog_vault.pub") charliejhadley_private_key <- file.path(key_dir, "blog_vault") add_user("charliejhadley", charliejhadley_public_key, vault = my_vault)
Once you’ve run this code, I’d recommend you explicitly comment out everything except for the first two lines.
Now we can add a secrets to the vault using
add_secret("ggmaps_fake_key", "foobar", user = "charliejhadley", vault = my_vault)
Personally, I’m deleting secrets from the
static/data/secret-keys.R after I add them. I’d recommend that you do the same. Remember that if you have not disabled your .RHistory then your keys will be available to ne’er-do-wells in a plain text file.
Now I can use my keys safely in blogposts, as follows:
library("here") library("secret") library("tidyverse") library("ggmap") my_vault <- here("static", "data", "secret-vault.vault") charliejhadley_private_key <- file.path("~/.ssh", "blog_vault") ggmaps_rstats_key <- get_secret("ggmap_key_2020", key = charliejhadley_private_key, vault = my_vault) register_google(key = ggmaps_rstats_key) base_map <- get_googlemap(center = c(2.2945, 48.858222), maptype = "roadmap") ggmap(base_map)
I highly recommend Hadley Wickham’s httr vignette on managing secrets if you want to learn more.