| Title: | Credential Chain for Seamless 'OAuth 2.0' Authentication to 'Azure Services' |
| Version: | 0.2.0 |
| Description: | Implements a credential chain for 'Azure OAuth 2.0' authentication based on the package 'httr2”s 'OAuth' framework. Sequentially attempts authentication methods until one succeeds. During development allows interactive browser-based flows ('Device Code' and 'Auth Code' flows) and non-interactive flow ('Client Secret') in batch mode. |
| License: | MIT + file LICENSE |
| Encoding: | UTF-8 |
| RoxygenNote: | 7.3.3 |
| URL: | https://pedrobtz.github.io/azr/, https://github.com/pedrobtz/azr |
| BugReports: | https://github.com/pedrobtz/azr/issues |
| Depends: | R (≥ 4.1) |
| Imports: | methods, utils, R6, cli, httr2 (≥ 1.2.1), jsonlite, rlang |
| Suggests: | data.table, httpuv, clipr, processx, testthat (≥ 3.0.0), vcr (≥ 2.0.0) |
| Config/testthat/edition: | 3 |
| NeedsCompilation: | no |
| Packaged: | 2025-12-04 05:24:42 UTC; pbtz |
| Author: | Pedro Baltazar [aut, cre] |
| Maintainer: | Pedro Baltazar <pedrobtz@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2025-12-04 05:40:02 UTC |
azr: Credential Chain for Seamless 'OAuth 2.0' Authentication to 'Azure Services'
Description
Implements a credential chain for 'Azure OAuth 2.0' authentication based on the package 'httr2”s 'OAuth' framework. Sequentially attempts authentication methods until one succeeds. During development allows interactive browser-based flows ('Device Code' and 'Auth Code' flows) and non-interactive flow ('Client Secret') in batch mode.
Author(s)
Maintainer: Pedro Baltazar pedrobtz@gmail.com
See Also
Useful links:
Report bugs at https://github.com/pedrobtz/azr/issues
Authorization code credential authentication
Description
Authenticates a user through the OAuth 2.0 authorization code flow. This flow opens a web browser for the user to sign in.
Details
The authorization code flow is the standard OAuth 2.0 flow for interactive authentication. It requires a web browser and is suitable for applications where the user can interact with a browser window.
The credential supports token caching to avoid repeated authentication. Tokens can be cached to disk or in memory. A redirect URI is required for the OAuth flow to complete.
Super classes
azr::Credential -> azr::InteractiveCredential -> AuthCodeCredential
Methods
Public methods
Inherited methods
Method new()
Create a new authorization code credential
Usage
AuthCodeCredential$new( scope = NULL, tenant_id = NULL, client_id = NULL, use_cache = "disk", offline = TRUE, redirect_uri = default_redirect_uri() )
Arguments
scopeA character string specifying the OAuth2 scope. Defaults to
NULL.tenant_idA character string specifying the Azure Active Directory tenant ID. Defaults to
NULL.client_idA character string specifying the application (client) ID. Defaults to
NULL.use_cacheA character string specifying the cache type. Use
"disk"for disk-based caching or"memory"for in-memory caching. Defaults to"disk".offlineA logical value indicating whether to request offline access (refresh tokens). Defaults to
TRUE.redirect_uriA character string specifying the redirect URI registered with the application. Defaults to
default_redirect_uri().
Returns
A new AuthCodeCredential object
Method get_token()
Get an access token using authorization code flow
Usage
AuthCodeCredential$get_token(reauth = FALSE)
Arguments
reauthA logical value indicating whether to force reauthentication. Defaults to
FALSE.
Returns
An httr2::oauth_token() object containing the access token
Method req_auth()
Add OAuth authorization code authentication to an httr2 request
Usage
AuthCodeCredential$req_auth(req)
Arguments
reqAn
httr2::request()object
Returns
The request object with OAuth authorization code authentication configured
Method clone()
The objects of this class are cloneable with this method.
Usage
AuthCodeCredential$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
# AuthCodeCredential requires an interactive session
## Not run:
# Create credential with default settings
cred <- AuthCodeCredential$new(
tenant_id = "your-tenant-id",
client_id = "your-client-id",
scope = "https://management.azure.com/.default"
)
# Get an access token (will open browser for authentication)
token <- cred$get_token()
# Force reauthentication
token <- cred$get_token(reauth = TRUE)
# Use with httr2 request
req <- httr2::request("https://management.azure.com/subscriptions")
req <- cred$req_auth(req)
## End(Not run)
Azure CLI credential authentication
Description
Authenticates using the Azure CLI (az) command-line tool. This credential
requires the Azure CLI to be installed and the user to be logged in via
az login.
Details
The credential uses the az account get-access-token command to retrieve
access tokens. It will use the currently active Azure CLI account and
subscription unless a specific tenant is specified.
Super class
azr::Credential -> AzureCLICredential
Public fields
.process_timeoutTimeout in seconds for Azure CLI command execution
Methods
Public methods
Inherited methods
Method new()
Create a new Azure CLI credential
Usage
AzureCLICredential$new( scope = NULL, tenant_id = NULL, process_timeout = NULL, login = FALSE, use_bridge = FALSE )
Arguments
scopeA character string specifying the OAuth2 scope. Defaults to
NULL, which uses the scope set during initialization.tenant_idA character string specifying the Azure Active Directory tenant ID. Defaults to
NULL, which uses the default tenant from Azure CLI.process_timeoutA numeric value specifying the timeout in seconds for the Azure CLI process. Defaults to
10.loginA logical value indicating whether to check if the user is logged in and perform login if needed. Defaults to
FALSE.use_bridgeA logical value indicating whether to use the device code bridge webpage during login. If
TRUE, launches an intermediate local webpage that displays the device code and facilitates copy-pasting before redirecting to the Microsoft device login page. Only used whenlogin = TRUE. Defaults toFALSE.
Returns
A new AzureCLICredential object
Method get_token()
Get an access token from Azure CLI
Usage
AzureCLICredential$get_token(scope = NULL)
Arguments
scopeA character string specifying the OAuth2 scope. If
NULL, uses the scope specified during initialization.
Returns
An httr2::oauth_token() object containing the access token
Method req_auth()
Add authentication to an httr2 request
Usage
AzureCLICredential$req_auth(req, scope = NULL)
Arguments
reqAn
httr2::request()objectscopeA character string specifying the OAuth2 scope. If
NULL, uses the scope specified during initialization.
Returns
The request object with authentication header added
Method account_show()
Show the currently active Azure CLI account information
Usage
AzureCLICredential$account_show(timeout = NULL)
Arguments
timeoutA numeric value specifying the timeout in seconds for the Azure CLI command. If
NULL, uses the process timeout specified during initialization.
Returns
A list containing the account information from Azure CLI
Method login()
Perform Azure CLI login using device code flow
Usage
AzureCLICredential$login()
Returns
Invisibly returns the exit status (0 for success, non-zero for failure)
Method logout()
Log out from Azure CLI
Usage
AzureCLICredential$logout()
Returns
Invisibly returns NULL
Method clone()
The objects of this class are cloneable with this method.
Usage
AzureCLICredential$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
# Create credential with default settings
cred <- AzureCLICredential$new()
# Create credential with specific scope and tenant
cred <- AzureCLICredential$new(
scope = "https://management.azure.com/.default",
tenant_id = "your-tenant-id"
)
# To get a token or authenticate a request it is required that
# 'az login' is successfully executed, otherwise it will return an error.
## Not run:
# Get an access token
token <- cred$get_token()
# Use with httr2 request
req <- httr2::request("https://management.azure.com/subscriptions")
resp <- httr2::req_perform(cred$req_auth(req))
## End(Not run)
Client secret credential authentication
Description
Authenticates a service principal using a client ID and client secret. This credential is commonly used for application authentication in Azure.
Details
The credential uses the OAuth 2.0 client credentials flow to obtain access tokens. It requires a registered Azure AD application with a client secret. The client secret should be stored securely and not hard-coded in scripts.
Super class
azr::Credential -> ClientSecretCredential
Methods
Public methods
Inherited methods
Method validate()
Validate the credential configuration
Usage
ClientSecretCredential$validate()
Details
Checks that the client secret is provided and not NA or NULL. Calls the parent class validation method.
Method get_token()
Get an access token using client credentials flow
Usage
ClientSecretCredential$get_token()
Returns
An httr2::oauth_token() object containing the access token
Method req_auth()
Add OAuth client credentials authentication to an httr2 request
Usage
ClientSecretCredential$req_auth(req)
Arguments
reqAn
httr2::request()object
Returns
The request object with OAuth client credentials authentication configured
Method clone()
The objects of this class are cloneable with this method.
Usage
ClientSecretCredential$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
# Create credential with client secret
cred <- ClientSecretCredential$new(
tenant_id = "your-tenant-id",
client_id = "your-client-id",
client_secret = "your-client-secret",
scope = "https://management.azure.com/.default"
)
# To get a token or authenticate a request it requires
# valid 'client_id' and 'client_secret' credentials,
# otherwise it will return an error.
## Not run:
# Get an access token
token <- cred$get_token()
# Use with httr2 request
req <- httr2::request("https://management.azure.com/subscriptions")
resp <- httr2::req_perform(cred$req_auth(req))
## End(Not run)
Device code credential authentication
Description
Authenticates a user through the device code flow. This flow is designed for devices that don't have a web browser or have input constraints.
Details
The device code flow displays a code that the user must enter on another device with a web browser to complete authentication. This is ideal for CLI applications, headless servers, or devices without a browser.
The credential supports token caching to avoid repeated authentication. Tokens can be cached to disk or in memory.
Super classes
azr::Credential -> azr::InteractiveCredential -> DeviceCodeCredential
Methods
Public methods
Inherited methods
Method new()
Create a new device code credential
Usage
DeviceCodeCredential$new( scope = NULL, tenant_id = NULL, client_id = NULL, use_cache = "disk", offline = TRUE )
Arguments
scopeA character string specifying the OAuth2 scope. Defaults to
NULL.tenant_idA character string specifying the Azure Active Directory tenant ID. Defaults to
NULL.client_idA character string specifying the application (client) ID. Defaults to
NULL.use_cacheA character string specifying the cache type. Use
"disk"for disk-based caching or"memory"for in-memory caching. Defaults to"disk".offlineA logical value indicating whether to request offline access (refresh tokens). Defaults to
TRUE.
Returns
A new DeviceCodeCredential object
Method get_token()
Get an access token using device code flow
Usage
DeviceCodeCredential$get_token(reauth = FALSE)
Arguments
reauthA logical value indicating whether to force reauthentication. Defaults to
FALSE.
Returns
An httr2::oauth_token() object containing the access token
Method req_auth()
Add OAuth device code authentication to an httr2 request
Usage
DeviceCodeCredential$req_auth(req)
Arguments
reqAn
httr2::request()object
Returns
The request object with OAuth device code authentication configured
Method clone()
The objects of this class are cloneable with this method.
Usage
DeviceCodeCredential$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
# DeviceCodeCredential requires an interactive session
## Not run:
# Create credential with default settings
cred <- DeviceCodeCredential$new()
# Get an access token (will prompt for 'device code' flow)
token <- cred$get_token()
# Force re-authentication
token <- cred$get_token(reauth = TRUE)
# Use with httr2 request
req <- httr2::request("https://management.azure.com/subscriptions")
req <- cred$req_auth(req)
## End(Not run)
Interactive credential base class
Description
Base class for interactive authentication credentials. This class should not be instantiated directly; use DeviceCodeCredential or AuthCodeCredential instead.
Super class
azr::Credential -> InteractiveCredential
Methods
Public methods
Inherited methods
Method is_interactive()
Check if the credential is interactive
Usage
InteractiveCredential$is_interactive()
Returns
Always returns TRUE for interactive credentials
Method clone()
The objects of this class are cloneable with this method.
Usage
InteractiveCredential$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Azure API Client
Description
An R6 class that provides a base HTTP client for interacting with Azure APIs. This client handles authentication, request building, retry logic, logging, and error handling for Azure API requests.
Details
The api_client class is designed to be a base class for Azure service-specific
clients. It provides:
Automatic authentication using Azure credentials
Configurable retry logic with exponential backoff
Request and response logging
JSON, XML, and HTML content type handling
Standardized error handling
Public fields
.host_urlBase URL for the API
.base_reqBase httr2 request object
.providerCredential provider R6 object
.credentialsCredentials function for authentication
.optionsRequest options (timeout, connecttimeout, max_tries)
.response_handlerOptional callback function to process response content
Methods
Public methods
Method new()
Create a new API client instance
Usage
api_client$new( host_url, provider = NULL, credentials = NULL, timeout = 60L, connecttimeout = 30L, max_tries = 5L, response_handler = NULL )
Arguments
host_urlA character string specifying the base URL for the API (e.g.,
"https://management.azure.com").providerAn R6 credential provider object that inherits from the
Credentialclass. If provided, the credential'sreq_authmethod will be used for authentication. Takes precedence overcredentials.credentialsA function that adds authentication to requests. If both
providerandcredentialsareNULL, usesdefault_non_auth(). The function should accept an httr2 request object and return a modified request with authentication.timeoutAn integer specifying the request timeout in seconds. Defaults to
60.connecttimeoutAn integer specifying the connection timeout in seconds. Defaults to
30.max_triesAn integer specifying the maximum number of retry attempts for failed requests. Defaults to
5.response_handlerAn optional function to process the parsed response content. The function should accept one argument (the parsed response) and return the processed content. If
NULL, usesdefault_response_handler()which converts data frames to data.table objects. Defaults toNULL.
Returns
A new api_client object
Method .fetch()
Make an HTTP request to the API
Usage
api_client$.fetch(
path,
...,
req_data = NULL,
req_method = "get",
verbosity = 0L,
content = c("body", "headers", "response", "request"),
content_type = NULL
)Arguments
pathA character string specifying the API endpoint path. Supports
glue::glue()syntax for variable interpolation using named arguments passed via.......Named arguments used for path interpolation with
glue::glue().req_dataRequest data. For GET requests, this is used as query parameters. For other methods, this is sent as JSON in the request body. Can be a list or character string (JSON).
req_methodA character string specifying the HTTP method. One of
"get","post","put","patch", or"delete". Defaults to"get".verbosityAn integer specifying the verbosity level for request debugging (passed to
httr2::req_perform()). Defaults to0.contentA character string specifying what to return. One of:
-
"body"(default): Return the parsed response body -
"headers": Return response headers -
"response": Return the full httr2 response object -
"request": Return the prepared request object without executing it
-
content_typeA character string specifying how to parse the response body. If
NULL, uses the response's Content-Type header. Common values:"application/json","application/xml","text/html".
Returns
Depends on the content parameter:
-
"body": Parsed response body (list, data.frame, or character) -
"headers": List of response headers -
"response": Fullhttr2::response()object -
"request":httr2::request()object
Method .req_build()
Build an HTTP request object
Usage
api_client$.req_build(path, ..., req_data = NULL, req_method = "get")
Arguments
pathA character string specifying the API endpoint path. Supports
glue::glue()syntax for variable interpolation using named arguments passed via.......Named arguments used for path interpolation with
glue::glue().req_dataRequest data. For GET requests, this is used as query parameters. For other methods, this is sent as JSON in the request body. Can be a list or character string (JSON).
req_methodA character string specifying the HTTP method. One of
"get","post","put","patch", or"delete". Defaults to"get".
Returns
An httr2::request() object ready for execution
Method .req_perform()
Perform an HTTP request and log the results
Usage
api_client$.req_perform(req, verbosity)
Arguments
reqAn
httr2::request()object to executeverbosityAn integer specifying the verbosity level for request debugging (passed to
httr2::req_perform()). Defaults to0.
Returns
An httr2::response() object containing the API response
Method .resp_content()
Extract and parse response content
Usage
api_client$.resp_content(resp, content_type = NULL)
Arguments
respAn
httr2::response()objectcontent_typeA character string specifying how to parse the response body. If
NULL, uses the response's Content-Type header. Common values:"application/json","application/xml","text/html".
Returns
Parsed response body. Format depends on content type:
JSON: List or data.frame
XML: xml2 document
HTML: xml2 document
Other: Character string
Method .get_token()
Get authentication token from the credential provider
Usage
api_client$.get_token()
Returns
An httr2::oauth_token() object if a provider is available,
otherwise returns NULL with a warning.
Method clone()
The objects of this class are cloneable with this method.
Usage
api_client$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
## Not run:
# Create a client with default credentials
client <- api_client$new(
host_url = "https://management.azure.com"
)
# Create a client with a credential provider
cred_provider <- get_credential_provider(
scope = "https://management.azure.com/.default"
)
client <- api_client$new(
host_url = "https://management.azure.com",
provider = cred_provider
)
# Create a client with custom credentials function
client <- api_client$new(
host_url = "https://management.azure.com",
credentials = my_credential_function,
timeout = 120,
max_tries = 3
)
# Create a client with custom response handler
custom_handler <- function(content) {
# Custom processing logic - e.g., keep data frames as-is
content
}
client <- api_client$new(
host_url = "https://management.azure.com",
response_handler = custom_handler
)
# Make a GET request
response <- client$.fetch(
path = "/subscriptions/{subscription_id}/resourceGroups",
subscription_id = "my-subscription-id",
req_method = "get"
)
## End(Not run)
Microsoft Graph API Resource
Description
An R6 class that extends api_resource to provide specialized methods for the Microsoft Graph API. This class adds convenience methods for common Graph operations.
Super class
azr::api_resource -> api_graph_resource
Methods
Public methods
Inherited methods
Method me()
Fetch the current user's profile
Usage
api_graph_resource$me(select = NULL)
Arguments
selectA character vector of properties to select (e.g., c("displayName", "mail")). If NULL, all properties are returned.
Returns
The response from the /me endpoint
Method clone()
The objects of this class are cloneable with this method.
Usage
api_graph_resource$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Azure API Resource
Description
An R6 class that wraps an api_client and adds an additional path segment
(like "beta" or "v1.0") to all requests. This is useful for APIs that version
their endpoints or have different API surfaces under different paths.
Details
The api_resource class creates a modified base request by appending an
endpoint path to the client's base request. All subsequent API calls through
this resource will automatically include this path prefix.
Public fields
.clientThe cloned api_client instance with modified base_req
Methods
Public methods
Method new()
Create a new API resource instance
Usage
api_resource$new(client, endpoint)
Arguments
clientAn
api_clientobject that provides the base HTTP client functionality. This will be cloned to avoid modifying the original.endpointA character string specifying the API endpoint or path segment to append (e.g.,
"v1.0","beta").
Returns
A new api_resource object
Method clone()
The objects of this class are cloneable with this method.
Usage
api_resource$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
## Not run:
# Create a client
client <- api_client$new(
host_url = "https://graph.microsoft.com"
)
# Create a resource with v1.0 API endpoint
resource_v1 <- api_resource$new(
client = client,
endpoint = "v1.0"
)
# Create a resource with beta API endpoint
resource_beta <- api_resource$new(
client = client,
endpoint = "beta"
)
# Make requests - the endpoint is automatically prepended
response <- resource_v1$.fetch(
path = "/me",
req_method = "get"
)
## End(Not run)
API Service Base Class
Description
Base R6 class for creating API service wrappers. This class provides a foundation for building service-specific API clients with authentication, endpoint management, and configuration.
Public fields
.clientAn api_client instance for making API requests
Methods
Public methods
Method new()
Create a new API service instance
Usage
api_service$new( client = NULL, chain = NULL, endpoints = list(), config = list() )
Arguments
clientAn api_client instance. If
NULL, a new client will be created.chainA credential_chain instance for authentication. Optional.
endpointsA named list where names are endpoint paths (e.g., "v1.0", "beta") and values are R6 class objects (not instances) to use for creating resources. Defaults to an empty list. If the value is
NULL, api_resource will be used.configA list of configuration options. Defaults to an empty list.
Returns
A new api_service object
Show Azure CLI Account Information
Description
Retrieves information about the currently active Azure CLI account and
subscription. This function runs az account show and parses the JSON
output into an R list.
Usage
az_cli_account_show(timeout = 10L)
Arguments
timeout |
An integer specifying the timeout in seconds for the Azure
CLI command. Defaults to |
Details
The function returns details about the current Azure subscription including:
Subscription ID and name
Tenant ID
Account state (e.g., "Enabled")
User information
Cloud environment details
Value
A list containing the account information from Azure CLI
Examples
## Not run:
# Get current account information
account_info <- az_cli_account_show()
# Access subscription ID
subscription_id <- account_info$id
# Access tenant ID
tenant_id <- account_info$tenantId
## End(Not run)
Get Access Token from Azure CLI
Description
Retrieves an access token from Azure CLI using the az account get-access-token
command. This is a lower-level function that directly interacts with the Azure
CLI to obtain OAuth2 tokens.
Usage
az_cli_get_token(scope, tenant_id = NULL, timeout = 10L)
Arguments
scope |
A character string specifying the OAuth2 scope for which to
request the access token (e.g., |
tenant_id |
A character string specifying the Azure Active Directory
tenant ID. If |
timeout |
A numeric value specifying the timeout in seconds for the
Azure CLI process. Defaults to |
Details
This function executes the Azure CLI command and parses the JSON response to create an httr2 OAuth token object. The token includes the access token, token type, and expiration time.
Value
An httr2::oauth_token() object containing:
-
access_token: The OAuth2 access token string -
token_type: The type of token (typically "Bearer") -
.expires_at: POSIXct timestamp when the token expires
Examples
## Not run:
# Get a token for Azure Resource Manager
token <- az_cli_get_token(
scope = "https://management.azure.com/.default"
)
# Get a token for a specific tenant
token <- az_cli_get_token(
scope = "https://graph.microsoft.com/.default",
tenant_id = "your-tenant-id"
)
# Access the token string
access_token <- token$access_token
## End(Not run)
Check if User is Logged in to Azure CLI
Description
Checks whether the user is currently logged in to Azure CLI by attempting to retrieve account information.
Usage
az_cli_is_login(timeout = 10L)
Arguments
timeout |
A numeric value specifying the timeout in seconds for the
Azure CLI command. Defaults to |
Value
A logical value: TRUE if the user is logged in, FALSE otherwise
Examples
## Not run:
# Check if logged in
if (az_cli_is_login()) {
message("User is logged in")
} else {
message("User is not logged in")
}
## End(Not run)
Azure CLI Device Code Login
Description
Performs an interactive Azure CLI login using device code flow. Automatically captures the device code, copies it to the clipboard, and opens the browser for authentication.
Usage
az_cli_login(tenant_id = NULL, use_bridge = FALSE, verbose = FALSE)
Arguments
tenant_id |
A character string specifying the Azure Active Directory
tenant ID to authenticate against. If |
use_bridge |
A logical value indicating whether to use the device code
bridge webpage. If |
verbose |
A logical value indicating whether to print detailed process
output to the console, including error messages from the Azure CLI process.
If |
Details
This function runs az login --use-device-code, monitors the output
to extract the device code, copies it to the clipboard, and opens
the authentication URL in the default browser.
Value
Invisibly returns the exit status (0 for success, non-zero for failure)
Examples
## Not run:
# Perform Azure CLI login with device code flow
az_cli_login()
# Use the bridge webpage for easier code handling
az_cli_login(use_bridge = TRUE)
# Login to a specific tenant with verbose output
az_cli_login(tenant_id = "your-tenant-id", verbose = TRUE)
## End(Not run)
Azure CLI Logout
Description
Logs out from Azure CLI by removing all stored credentials and account
information. This function runs az logout.
Usage
az_cli_logout()
Details
After logging out, you will need to run az_cli_login() again to
authenticate and use Azure CLI credentials.
Value
Invisibly returns NULL
Examples
## Not run:
# Log out from Azure CLI
az_cli_logout()
## End(Not run)
Create a Microsoft Graph API Client
Description
Creates a configured client for the Microsoft Graph API with authentication and versioned endpoints (v1.0 and beta). This function returns an api_service object that provides access to Microsoft Graph resources through versioned endpoints.
Usage
azr_graph_client(scopes = ".default", ..., chain = NULL)
Arguments
scopes |
A character string specifying the OAuth2 scope suffix to be appended
to the Graph API URL. Defaults to |
... |
Additional arguments passed to the api_client constructor. |
chain |
A credential_chain instance for authentication. If NULL,
a default credential chain will be created using |
Details
The function creates a Microsoft Graph service using these components:
-
api_client: A general-purpose API client configured with the Graph API host URL (
https://graph.microsoft.com) and authentication provider. -
api_graph_resource: A specialized resource class that extends api_resource with Microsoft Graph-specific methods. Currently implements:
-
me(select = NULL): Fetch the current user's profile. Theselectparameter accepts a character vector of properties to return (e.g.,c("displayName", "mail")).
-
-
api_service: A service container that combines the client and resources with versioned endpoints (v1.0 and beta). The service is locked using
lockEnvironment()to prevent modification after creation.
Value
An api_service object configured for Microsoft Graph API with
v1.0 and beta endpoints. The object is locked using lockEnvironment() to
prevent modification after creation. Access endpoints via $v1.0 or $beta.
Examples
## Not run:
# Create a Graph API client with default credentials
graph <- azr_graph_client()
# Fetch current user profile from v1.0 endpoint
me <- graph$v1.0$me()
# Fetch specific properties using OData $select
me <- graph$v1.0$me(select = c("displayName", "mail", "userPrincipalName"))
# Use beta endpoint for preview features
me_beta <- graph$beta$me(select = c("displayName", "mail"))
# Create with a custom credential chain
custom_chain <- credential_chain(
AzureCLICredential$new(scope = "https://graph.microsoft.com/.default")
)
graph <- azr_graph_client(chain = custom_chain)
# Use specific scopes instead of .default
graph <- azr_graph_client(scopes = "User.Read Mail.Read")
## End(Not run)
Azure Authority Host URLs
Description
Login endpoint URLs for different Azure cloud environments.
Usage
azure_authority_hosts
Format
An object of class list of length 3.
Azure Default Client Configuration
Description
Default client ID and tenant ID used for Azure authentication when not explicitly provided. The client ID is Microsoft's public Azure CLI client ID.
Usage
azure_client
Format
An object of class list of length 2.
Common Azure OAuth Scopes
Description
Predefined OAuth scopes for common Azure services.
Usage
azure_scopes
Format
An object of class list of length 5.
Create Custom Credential Chain
Description
Creates a custom chain of credential providers to attempt during authentication. Credentials are tried in the order they are provided until one successfully authenticates. This allows you to customize the authentication flow beyond the default credential chain.
Usage
credential_chain(...)
Arguments
... |
Named credential objects or credential classes. Each element
should be a credential class (e.g., |
Value
A credential_chain object containing the specified sequence
of credential providers.
See Also
default_credential_chain(), get_token_provider()
Examples
# Create a custom chain with only non-interactive credentials
custom_chain <- credential_chain(
client_secret = ClientSecretCredential,
azure_cli = AzureCLICredential
)
# Use the custom chain to get a token
## Not run:
token <- get_token(
scope = "https://graph.microsoft.com/.default",
chain = custom_chain
)
## End(Not run)
Get default Azure client ID
Description
Retrieves the Azure client ID from the AZURE_CLIENT_ID environment variable,
or falls back to the default Azure CLI client ID if not set.
Usage
default_azure_client_id()
Value
A character string with the client ID
Examples
default_azure_client_id()
Get default Azure client secret
Description
Retrieves the Azure client secret from the AZURE_CLIENT_SECRET environment
variable, or returns NA_character_ if not set.
Usage
default_azure_client_secret()
Value
A character string with the client secret, or NA_character_ if not set
Examples
default_azure_client_secret()
Get default Azure configuration directory
Description
Retrieves the Azure configuration directory from the AZURE_CONFIG_DIR
environment variable, or falls back to the platform-specific default.
Usage
default_azure_config_dir()
Value
A character string with the Azure configuration directory path
Examples
default_azure_config_dir()
Get default Azure authority host
Description
Retrieves the Azure authority host from the AZURE_AUTHORITY_HOST environment
variable, or falls back to Azure Public Cloud if not set.
Usage
default_azure_host()
Value
A character string with the authority host URL
Examples
default_azure_host()
Create default Azure OAuth client
Description
Creates an httr2::oauth_client() configured for Azure authentication.
Usage
default_azure_oauth_client(
client_id = default_azure_client_id(),
client_secret = NULL,
name = NULL
)
Arguments
client_id |
A character string specifying the client ID. Defaults to
|
client_secret |
A character string specifying the client secret. Defaults
to |
name |
A character string specifying the client name. Defaults to |
Value
An httr2::oauth_client() object
Examples
client <- default_azure_oauth_client()
client <- default_azure_oauth_client(
client_id = "my-client-id",
client_secret = "my-secret"
)
Get default Azure OAuth scope
Description
Returns the default OAuth scope for a specified Azure resource.
Usage
default_azure_scope(resource = "azure_arm")
Arguments
resource |
A character string specifying the Azure resource. Must be one of:
|
Value
A character string with the OAuth scope URL
Examples
default_azure_scope()
default_azure_scope("azure_graph")
Get default Azure tenant ID
Description
Retrieves the Azure tenant ID from the AZURE_TENANT_ID environment variable,
or falls back to the default value if not set.
Usage
default_azure_tenant_id()
Value
A character string with the tenant ID
Examples
default_azure_tenant_id()
Get default Azure OAuth URLs
Description
Constructs Azure OAuth 2.0 endpoint URLs for a given tenant and authority host.
Usage
default_azure_url(
endpoint = NULL,
oauth_host = default_azure_host(),
tenant_id = default_azure_tenant_id()
)
Arguments
endpoint |
A character string specifying which endpoint URL to return.
Must be one of: |
oauth_host |
A character string specifying the Azure authority host.
Defaults to |
tenant_id |
A character string specifying the tenant ID. Defaults to
|
Value
If endpoint is specified, returns a character string with the URL.
If endpoint is NULL, returns a named list of all endpoint URLs.
Examples
# Get all URLs
default_azure_url()
# Get specific endpoint
default_azure_url("token")
# Custom tenant
default_azure_url("authorize", tenant_id = "my-tenant-id")
Create Default Credential Chain
Description
Creates the default chain of credentials to attempt during authentication. The credentials are tried in order until one successfully authenticates. The default chain includes:
Client Secret Credential - Uses client ID and secret
Authorization Code Credential - Interactive browser-based authentication
Azure CLI Credential - Uses credentials from Azure CLI
Device Code Credential - Interactive device code flow
Usage
default_credential_chain()
Value
A credential_chain object containing the default sequence of
credential providers.
See Also
credential_chain(), get_token_provider()
Default No Authentication
Description
A pass-through credential function that performs no authentication. This function returns the request object unchanged, allowing API calls to be made without adding any authentication headers or tokens.
Usage
default_non_auth(req)
Arguments
req |
An |
Value
The same httr2::request() object, unmodified
Get default OAuth redirect URI
Description
Constructs a redirect URI for OAuth flows. If the provided URI doesn't have
a port, assigns a random port using httpuv::randomPort().
Usage
default_redirect_uri(redirect_uri = httr2::oauth_redirect_uri())
Arguments
redirect_uri |
A character string specifying the redirect URI. Defaults
to |
Value
A character string with the redirect URI
Examples
default_redirect_uri()
Default Response Handler
Description
Default callback function for processing API response content. This function converts data frames within lists to data.table objects for better performance and functionality, if the data.table package is available.
Usage
default_response_handler()
Details
The function recursively processes list responses and converts any data.frame
objects to data.table objects using data.table::as.data.table(), but only
if the data.table package is installed. If data.table is not available,
data frames are returned unchanged. Non-data.frame elements are always
returned unchanged.
Value
A function that accepts parsed response content and returns processed content
Examples
# Get the default handler
handler <- default_response_handler()
# Use with a custom handler
custom_handler <- function(content) {
# Your custom processing logic
content
}
Azure Environment Variable Names
Description
Standard environment variable names used for Azure credential discovery.
Usage
environment_variables
Format
An object of class list of length 9.
Get Credential Authentication Function
Description
Creates a function that retrieves authentication tokens and formats them as HTTP Authorization headers. This function handles credential discovery and returns a callable method that generates Bearer token headers when invoked.
Usage
get_credential_auth(
scope = NULL,
tenant_id = NULL,
client_id = NULL,
client_secret = NULL,
use_cache = "disk",
offline = TRUE,
chain = default_credential_chain()
)
Arguments
scope |
Optional character string specifying the authentication scope. |
tenant_id |
Optional character string specifying the tenant ID for authentication. |
client_id |
Optional character string specifying the client ID for authentication. |
client_secret |
Optional character string specifying the client secret for authentication. |
use_cache |
Character string indicating the caching strategy. Defaults
to |
offline |
Logical. If |
chain |
A list of credential objects, where each element must inherit
from the |
Value
A function that, when called, returns a named list with an
Authorization element containing the Bearer token, suitable for use
with httr2::req_headers().
See Also
get_token(), get_request_authorizer(), get_token_provider()
Examples
## Not run:
# Create an authentication function
auth_fn <- get_credential_auth(
scope = "https://graph.microsoft.com/.default"
)
# Call it to get headers
auth_headers <- auth_fn()
# Use with httr2
req <- httr2::request("https://graph.microsoft.com/v1.0/me") |>
httr2::req_headers(!!!auth_headers)
## End(Not run)
Get Credential Provider
Description
Discovers and returns an authenticated credential object from a chain of credential providers. This function attempts each credential in the chain until one successfully authenticates, returning the first successful credential object.
Usage
get_credential_provider(
scope = NULL,
tenant_id = NULL,
client_id = NULL,
client_secret = NULL,
use_cache = "disk",
offline = TRUE,
oauth_host = NULL,
oauth_endpoint = NULL,
chain = NULL
)
Arguments
scope |
Optional character string specifying the authentication scope. |
tenant_id |
Optional character string specifying the tenant ID for authentication. |
client_id |
Optional character string specifying the client ID for authentication. |
client_secret |
Optional character string specifying the client secret for authentication. |
use_cache |
Character string indicating the caching strategy. Defaults
to |
offline |
Logical. If |
oauth_host |
Optional character string specifying the OAuth host URL. |
oauth_endpoint |
Optional character string specifying the OAuth endpoint. |
chain |
A list of credential objects, where each element must inherit
from the |
Value
A credential object that inherits from the Credential class and
has successfully authenticated.
See Also
get_token_provider(), get_request_authorizer(),
default_credential_chain()
Examples
## Not run:
# Get a credential provider with default settings
cred <- get_credential_provider(
scope = "https://graph.microsoft.com/.default",
tenant_id = "my-tenant-id"
)
# Use the credential to get a token
token <- cred$get_token()
## End(Not run)
Get Default Request Authorizer Function
Description
Creates a request authorizer function that retrieves authentication credentials and returns a callable request authorization method. This function handles the credential discovery process and returns the request authentication method from the discovered credential object.
Usage
get_request_authorizer(
scope = NULL,
tenant_id = NULL,
client_id = NULL,
client_secret = NULL,
use_cache = "disk",
offline = TRUE,
chain = default_credential_chain()
)
Arguments
scope |
Optional character string specifying the authentication scope. |
tenant_id |
Optional character string specifying the tenant ID for authentication. |
client_id |
Optional character string specifying the client ID for authentication. |
client_secret |
Optional character string specifying the client secret for authentication. |
use_cache |
Character string indicating the caching strategy. Defaults
to |
offline |
Logical. If |
chain |
A list of credential objects, where each element must inherit
from the |
Value
A function that authorizes HTTP requests with appropriate credentials when called.
See Also
get_token_provider(), get_token()
Examples
# In non-interactive sessions, this function will return an error if the
# environment is not setup with valid credentials. And in an interactive session
# the user will be prompted to attempt one of the interactive authentication flows.
## Not run:
req_auth <- get_request_authorizer(
scope = "https://graph.microsoft.com/.default"
)
req <- req_auth(httr2::request("https://graph.microsoft.com/v1.0/me"))
## End(Not run)
Get Authentication Token
Description
Retrieves an authentication token using the default token provider. This is a convenience function that combines credential discovery and token acquisition in a single step.
Usage
get_token(
scope = NULL,
tenant_id = NULL,
client_id = NULL,
client_secret = NULL,
use_cache = "disk",
offline = TRUE,
chain = default_credential_chain()
)
Arguments
scope |
Optional character string specifying the authentication scope. |
tenant_id |
Optional character string specifying the tenant ID for authentication. |
client_id |
Optional character string specifying the client ID for authentication. |
client_secret |
Optional character string specifying the client secret for authentication. |
use_cache |
Character string indicating the caching strategy. Defaults
to |
offline |
Logical. If |
chain |
A list of credential objects, where each element must inherit
from the |
Value
An httr2::oauth_token() object.
See Also
get_token_provider(), get_request_authorizer()
Examples
# In non-interactive sessions, this function will return an error if the
# environment is not setup with valid credentials. And in an interactive session
# the user will be prompted to attempt one of the interactive authentication flows.
## Not run:
token <- get_token(
scope = "https://graph.microsoft.com/.default",
tenant_id = "my-tenant-id",
client_id = "my-client-id",
client_secret = "my-secret"
)
## End(Not run)
Get Default Token Provider Function
Description
Creates a token provider function that retrieves authentication credentials and returns a callable token getter. This function handles the credential discovery process and returns the token acquisition method from the discovered credential object.
Usage
get_token_provider(
scope = NULL,
tenant_id = NULL,
client_id = NULL,
client_secret = NULL,
use_cache = "disk",
offline = TRUE,
chain = default_credential_chain()
)
Arguments
scope |
Optional character string specifying the authentication scope. |
tenant_id |
Optional character string specifying the tenant ID for authentication. |
client_id |
Optional character string specifying the client ID for authentication. |
client_secret |
Optional character string specifying the client secret for authentication. |
use_cache |
Character string indicating the caching strategy. Defaults
to |
offline |
Logical. If |
chain |
A list of credential objects, where each element must inherit
from the |
Value
A function that retrieves and returns an authentication token when called.
See Also
get_request_authorizer(), get_token()
Examples
# In non-interactive sessions, this function will return an error if the
# environment is not set up with valid credentials. In an interactive session
# the user will be prompted to attempt one of the interactive authentication flows.
## Not run:
token_provider <- get_token_provider(
scope = "https://graph.microsoft.com/.default",
tenant_id = "my-tenant-id",
client_id = "my-client-id",
client_secret = "my-secret"
)
token <- token_provider()
## End(Not run)
Detect if running in a hosted session
Description
Determines whether the current R session is running in a hosted environment such as Google Colab or RStudio Server (non-localhost).
Usage
is_hosted_session()
Details
This function checks for:
Google Colab: presence of the
COLAB_RELEASE_TAGenvironment variableRStudio Server:
RSTUDIO_PROGRAM_MODEis "server" andRSTUDIO_HTTP_REFERERdoes not contain "localhost"
Value
A logical value: TRUE if running in a hosted session (Google Colab
or remote RStudio Server), FALSE otherwise.
Examples
if (is_hosted_session()) {
message("Running in a hosted environment")
}