| api_security_cors | R Documentation |
This function adds Cross-Origin Resource Sharing (CORS) to a path in your API. The function can be called multiple times to set up CORS for multiple paths, potentially with different settings for each path. CORS is a complex specification and more can be read about it at the CORS plugin documentation.
api_security_cors(
api,
path = "/*",
origin = "*",
methods = c("get", "head", "put", "patch", "post", "delete"),
allowed_headers = NULL,
exposed_headers = NULL,
allow_credentials = FALSE,
max_age = NULL
)
api |
A plumber2 api object to add the plugin to |
path |
The path that the policy should apply to. routr path syntax applies, meaning that wilcards and path parameters are allowed. |
origin |
The origin allowed for the path. Can be one of:
|
methods |
The HTTP methods allowed for the |
allowed_headers |
A character vector of request headers allowed when
making the request. If the request contains headers not permitted, then
the response will be blocked by the browser. |
exposed_headers |
A character vector of response headers that should be made available to the client upon a succesful request |
allow_credentials |
A boolean indicating whether credentials are
allowed in the request. Credentials are cookies or HTTP authentication
headers, which are normally stripped from |
max_age |
The duration browsers are allowed to keep the preflight response in the cache |
This functions return the api object allowing for easy chaining
with the pipe
To add CORS to a path you can add @cors <origin> to a
handler annotation. <origin> must be one or more URLs or *, separated by
comma (meaning it is not possible to provide a function using the annotation).
This will add CORS to all endpoints described in the block. The annotation
doesn't allow setting allowed_headers, exposed_headers,
allow_credentials or max_age and the default values will be used.
#* A handler for /user/<username>
#*
#* @param username:string The name of the user to provide information on
#*
#* @get /user/<username>
#*
#* @response 200:{name:string, age:integer, hobbies:[string]} Important
#* information about the user such as their name, age, and hobbies
#*
#* @cors https://example.com, https://another-site.com
#*
function(username) {
find_user_in_db(username)
}
Other security features:
api_security_headers(),
api_security_resource_isolation()
# Set up cors for your asset/ path for the https://examples.com origin
api() |>
api_security_cors(
path = "asset/*",
origin = "https://examples.com"
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.