Generating OAuth tokens from a server


You can generate OAuth tokens from the httr package using the oauth2.0_token command. If you have the httpuv package installled, the process for generating new tokens will dynamically open a new browser window. If you use R on a desktop, this process should work well. However, if you use R on a server, you may eventually be redirected to the localhost on port 1410 and receive an error:

Chrome: This site can't be reached; localhost refused to connect.
Firefox: Unable to connect; can't establish a connection.

The simplest solution for generating an OAuth ticket from R on a server is to set the out of band option equal to true before executing oauth2.0_token:


Generate a token with the OOB option

Sometimes you need to create an OAuth token when you want R to communicate with other online services. For example, googlesheets allows you to access and manage Google spreadsheets from R but it requires you to create a .httr-oauth token via the httr package. The simplest way to create a .httr-oauth token from a server is to set the httr_oob_default option to true, which will tell httr to use the out of band method for authenticating. You will be given a URL and be expected to return an authorization code.

gs_auth(new_user = TRUE) 

The gs_auth command calls the oauth2.0_token command which prompts you to paste a URL into the browser. Once you authenticate through the browser you should be given an authorization code that you can paste back inside your R session.  

> gs_auth(new_user = TRUE)
No token currently in force.
Please point your browser to the following url:

Enter authorization code:

After you enter the authorization code httr will create a new token and store it in .httr-auth.

Generate a token without the OOB option

Alternatively, you can create a .httr-oauth token manually using httr commands. Use the out of band authentication mode by setting use_oob=TRUE in the oauth2.0_token command.


file.remove('.httr-oauth') # Remove current token

   endpoint = oauth_endpoints("google"),
   app = oauth_app(
      key = getOption("googlesheets.client_id"), 
      secret = getOption("googlesheets.client_secret")
   scope = c(
   use_oob = TRUE,
   cache = TRUE

gs_ls() # Test

One thing httr does when you set the httr_oob_default option is to redefine the URI to redirect_uri <- "urn:ietf:wg:oauth:2.0:oob" as seen in the code for oauth-init.

Copy-paste to server

Finally, a less elegant solution is to create the .httr-oauth token on your desktop and then copy the file to a server.

Have more questions? Submit a request


Powered by Zendesk