3 Exchanging and storing tokens

The token you provide to the user needs to be stored on their machine so that they can later send it back in the request to your plumber API. Where and how the token is stored depends on your use case and what the service making the requests to your API looks like.

3.1 Exchanging tokens

3.1.1 Issueing the token

When you first issue a token to the user - i.e. in the authentication endpoint of our examples - , you have two options how you want to return it to them: send it as part of the HTTP response or set a token in the browser of the user.

3.1.1.1 Return in HTTP response

Return the token in the HTTP response by including the appropriate return statement at the end of your authentication endpoint.

pr$handle("POST", "/authentication", function (req, res, user = NULL, password = NULL) {

  # ... 
  # CODE HERE
  # ...
  
  # return jwt as response
  return(jwt = jwt)
}, preempt = c("sealr-jwt"))

This is the most flexible way as it allows the user to handle the token according to their needs. They could…

  • … store the token somewhere and later include it in an R script or R Markdown. For example, if the user wants to generate reports and needs to use your API in order to do this. They should take care to follow guidelines on how to securely manage credentials and never include the token in their scripts.
  • … store the token in their web browser’s local storage. The local storage of a web browser is. This is relevant if the user makes the request from a web application from their browser (see . The implementation of the storing mechanism would be part of the frontend code. All frontend oriented languages support storing

3.1.3 HTTP Authorization header

3.1.4 Interactive R session

If your users simply use the token to make requests from an R script, e.g. by executing an .R file or generating an R markdown file, they should store their token in a secure way.

Some resources to get started: - https://db.rstudio.com/best-practices/managing-credentials/

3.1.5 Another application

Another service

3.1.6 Web application

Finally, you could have a “typical” web frontend-backend infrastructure where you want to use plumber to serve data to a frontend that your user can visit in their Internet browser.

Typically, in web development, there are two approaches to storing user data.

3.2 Local Storage