You can use Renviron.site or .Renviron to store and access private data into your shiny application. (see here for Hadley Wickham's recommendations and instructions - ref example below).
Solution:
If your package supports an authentication workflow based on an API key or token, encourage users to store it in an environment variable. We illustrate this using the github R package, which wraps the Github v3 API. Tailor this template to your API + package and include in README.md or a vignette.
- Create a personal access token in the Personal access tokens area of
your GitHub personal settings. Copy token to the clipboard.
- Identify your home directory. Not sure? Enter normalizePath("~/") in the R
console.
- Create a new text file. If in RStudio, do File > New File >
Text file.
Create a line like this:
GITHUB_PAT=blahblahblahblahblahblah
where the name GITHUB_PAT
reminds you which API this is for and blahblahblahblahblahblah
is your personal access token, pasted from the clipboard.
Make sure the last line in the file is empty (if it isn’t R will silently fail to load the file. If you’re using an editor that shows line numbers, there should be two lines, where the second one is empty.
Save in your home directory with the filename .Renviron. If questioned,
YES you do want to use a filename that begins with a dot ..
- Note that by default dotfiles are usually hidden. But within RStudio, the file browser will make .Renviron visible and therefore easy to edit in the future.
Restart R. .Renviron is processed only at the start of an R session.
Use Sys.getenv() to access your token. For example, here’s how to use your GITHUB_PAT with the github package:
library(github)
ctx <- create.github.context(access_token = Sys.getenv("GITHUB_PAT"))
# ... proceed to use other package functions to open issues, etc.
FAQ: Why define this environment variable via .Renviron instead of in .bash_profile or .bashrc?
Because there are many combinations of OS and ways of running R where the .Renviron approach “just works” and the bash stuff does not. When R is a child process of, say, Emacs or RStudio, you can’t always count on environment variables being passed to R. Put them in an R-specific start-up file and save yourself some grief.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…