As a former security reporter, it makes me a little queasy to store a password or token in plain text. And that’s basically what happens when you store a password or token string in an R environment variable.
The good news is that if you use R environment variables, they don’t show up in your environment tab. And, if you share your code with someone or post the code on GitHub, you won’t reveal your credentials by mistake.
The bad news is that an R environment file is a plain text file, dot Renviron. You can see that file if you run
Using the keyring package is a better idea.
Install it from CRAN with the usual
install.packages("keyring") and then load it with
You can then store a value in the keyring from R with the
key_set() function. For example,
key_set("MY_FAKE_TOKEN") to store a value for MY_FAKE_TOKEN. You’ll be asked to enter a “password,” which is actually how you enter the value you want to securely store. By using the password dialog box, you can set the value once interactively and never have to type the value in clear text.
When using keyring’s
set_key() function, you can enter the value in a password field interactively.
The best way to use a value that’s stored in a keyring is as an argument within a function. That way, the actual values never show up in your environment tab or history, as they would if you stored the value in a new variable in your script.
You can access the value with the
key_get() function, such as
key_get("MY_FAKE_TOKEN"), and then use it in an argument such as setting an option:
options(googleAuthR.client_id = key_get("MY_FAKE_TOKEN"))
This still isn’t very secure. It’s a big improvement that your credentials are stored in an encrypted keyring. But anyone who can access your machine and knows about the keyring package can still get to your credentials.
keyring_list() will show all the available entries in the keyring, if not their values.
To add a layer of security, you can create a keyring that’s password-protected within R. Do that with
keyring_create() and the name of a new keyring, such as
You’ll be asked for a password using the same type of password dialog box as when setting a value with the
You can unlock a password-protected keyring called Rcredentials at the start of an R session with
keyring_unlock("Rcredentials"). Now you can set a value for a new token, specifying the new keyring, with code such as
key_set("NEW_FAKE_TOKEN", keyring ="Rcredentials") .
And, you can retrieve a value the same way as before, but specifying the keyring
key_get("NEW_FAKE_TOKEN", keyring ="Rcredentials")
Finally, you can lock the keyring at the end of your script with
After locking the keyring, if you (or anyone else) run
key_get("NEW_FAKE_TOKEN"), you (or they) will be asked for the keyring password.
And now, you’ve got some more security for your passwords and tokens in R.