Skip to contents

Configures the package auth state to use a provided token for subsequent API calls. This is for Plumber APIs and other server-side code that receives authenticated requests and needs to make downstream API calls on behalf of the user.

You probably don't need this for interactive use. Use auth_login() instead, which handles authentication automatically.

Usage

auth_use_token(
  token,
  validate = FALSE,
  expires_in = 3600,
  project_id = NULL,
  realm = "counts"
)

Arguments

token

Character. The API token, with or without "Bearer " prefix.

validate

Logical. If TRUE, validates the token via auth_validate() before setting state. Default FALSE assumes the caller has already validated the token.

expires_in

Numeric. Assumed token lifetime in seconds. Default 3600. Note: this is an estimate; the actual token may expire sooner.

project_id

Integer. Project ID for validation. Only used when validate = TRUE.

realm

Character. The realm to set the token for (default "counts").

Value

Logical (invisibly). TRUE if the token was set successfully, FALSE if validation failed (only possible when validate = TRUE).

Details

Typical usage (Plumber filter)

#* @filter auth
function(req, res) {
  token <- req$HEADERS["authorization"]
  if (spdgt.auth::auth_use_token(token, validate = TRUE)) {
    plumber::forward()
  } else {
    res$status <- 401
    list(error = "Unauthorized")
  }
}

Security notes

  • The auth state is global. In concurrent request scenarios, ensure each request completes its API calls before the next request modifies state.

  • When validate = FALSE, the caller is responsible for ensuring the token is valid.

See also

auth_validate() for token validation, auth_login() for interactive authentication

Examples

if (FALSE) { # \dontrun{
# Use a token without validation
auth_use_token("eyJhbGci...")

# Use with validation
auth_use_token(req$HEADERS["authorization"], validate = TRUE)

# Use for a specific realm
auth_use_token(token, realm = "telemetry")
} # }