Skip to main content

SalesforceCredentials

Struct SalesforceCredentials 

Source
pub struct SalesforceCredentials { /* private fields */ }
Expand description

Standard Salesforce credentials implementation.

Sensitive fields (access_token, refresh_token) are redacted in Debug output to prevent accidental exposure in logs.

Implementations§

Source§

impl SalesforceCredentials

Source

pub fn new( instance_url: impl Into<String>, access_token: impl Into<String>, api_version: impl Into<String>, ) -> SalesforceCredentials

Create new credentials with the given values.

Source

pub fn with_refresh_token( self, refresh_token: impl Into<String>, ) -> SalesforceCredentials

Create credentials with a refresh token.

Source

pub fn refresh_token(&self) -> Option<&str>

Get the refresh token if available.

Examples found in repository?
examples/basic_auth.rs (line 53)
44async fn example_from_env() -> Result<(), Box<dyn std::error::Error>> {
45    println!("Example 1: Load from Environment Variables");
46    println!("-------------------------------------------");
47
48    match SalesforceCredentials::from_env() {
49        Ok(creds) => {
50            println!("✓ Loaded credentials from environment");
51            println!("  Instance URL: {}", creds.instance_url());
52            println!("  API Version: {}", creds.api_version());
53            println!("  Has Refresh Token: {}", creds.refresh_token().is_some());
54        }
55        Err(e) => {
56            println!("✗ Failed to load from environment: {}", e);
57            println!("  Tip: Set SF_INSTANCE_URL and SF_ACCESS_TOKEN");
58        }
59    }
60
61    println!();
62    Ok(())
63}
Source

pub fn set_access_token(&mut self, token: impl Into<String>)

Set a new access token (e.g., after refresh).

Source

pub fn from_env() -> Result<SalesforceCredentials, Error>

Load credentials from environment variables.

Required environment variables:

  • SF_INSTANCE_URL or SALESFORCE_INSTANCE_URL
  • SF_ACCESS_TOKEN or SALESFORCE_ACCESS_TOKEN

Optional:

  • SF_API_VERSION or SALESFORCE_API_VERSION (default: “62.0”)
  • SF_REFRESH_TOKEN or SALESFORCE_REFRESH_TOKEN
Examples found in repository?
examples/basic_auth.rs (line 48)
44async fn example_from_env() -> Result<(), Box<dyn std::error::Error>> {
45    println!("Example 1: Load from Environment Variables");
46    println!("-------------------------------------------");
47
48    match SalesforceCredentials::from_env() {
49        Ok(creds) => {
50            println!("✓ Loaded credentials from environment");
51            println!("  Instance URL: {}", creds.instance_url());
52            println!("  API Version: {}", creds.api_version());
53            println!("  Has Refresh Token: {}", creds.refresh_token().is_some());
54        }
55        Err(e) => {
56            println!("✗ Failed to load from environment: {}", e);
57            println!("  Tip: Set SF_INSTANCE_URL and SF_ACCESS_TOKEN");
58        }
59    }
60
61    println!();
62    Ok(())
63}
More examples
Hide additional examples
examples/bulk_operations.rs (line 290)
284async fn get_credentials() -> Result<SalesforceCredentials, Box<dyn std::error::Error>> {
285    if let Ok(creds) = SalesforceCredentials::from_sfdx_alias("default").await {
286        println!("✓ Using credentials from Salesforce CLI\n");
287        return Ok(creds);
288    }
289
290    match SalesforceCredentials::from_env() {
291        Ok(creds) => {
292            println!("✓ Using credentials from environment variables\n");
293            Ok(creds)
294        }
295        Err(e) => {
296            eprintln!("✗ Failed to load credentials: {}", e);
297            eprintln!("\nPlease either:");
298            eprintln!("  1. Authenticate with Salesforce CLI: sf org login web");
299            eprintln!("  2. Set environment variables: SF_INSTANCE_URL, SF_ACCESS_TOKEN");
300            Err(e.into())
301        }
302    }
303}
examples/error_handling.rs (line 318)
312async fn get_credentials() -> Result<SalesforceCredentials, Box<dyn std::error::Error>> {
313    if let Ok(creds) = SalesforceCredentials::from_sfdx_alias("default").await {
314        println!("✓ Using credentials from Salesforce CLI\n");
315        return Ok(creds);
316    }
317
318    match SalesforceCredentials::from_env() {
319        Ok(creds) => {
320            println!("✓ Using credentials from environment variables\n");
321            Ok(creds)
322        }
323        Err(e) => {
324            eprintln!("✗ Failed to load credentials: {}", e);
325            eprintln!("\nPlease either:");
326            eprintln!("  1. Authenticate with Salesforce CLI: sf org login web");
327            eprintln!("  2. Set environment variables: SF_INSTANCE_URL, SF_ACCESS_TOKEN");
328            Err(e.into())
329        }
330    }
331}
examples/queries.rs (line 432)
426async fn get_credentials() -> Result<SalesforceCredentials, Box<dyn std::error::Error>> {
427    if let Ok(creds) = SalesforceCredentials::from_sfdx_alias("default").await {
428        println!("✓ Using credentials from Salesforce CLI\n");
429        return Ok(creds);
430    }
431
432    match SalesforceCredentials::from_env() {
433        Ok(creds) => {
434            println!("✓ Using credentials from environment variables\n");
435            Ok(creds)
436        }
437        Err(e) => {
438            eprintln!("✗ Failed to load credentials: {}", e);
439            eprintln!("\nPlease either:");
440            eprintln!("  1. Authenticate with Salesforce CLI: sf org login web");
441            eprintln!("  2. Set environment variables: SF_INSTANCE_URL, SF_ACCESS_TOKEN");
442            Err(e.into())
443        }
444    }
445}
examples/rest_crud.rs (line 303)
295async fn get_credentials() -> Result<SalesforceCredentials, Box<dyn std::error::Error>> {
296    // Try SFDX first
297    if let Ok(creds) = SalesforceCredentials::from_sfdx_alias("default").await {
298        println!("✓ Using credentials from Salesforce CLI\n");
299        return Ok(creds);
300    }
301
302    // Fall back to environment variables
303    match SalesforceCredentials::from_env() {
304        Ok(creds) => {
305            println!("✓ Using credentials from environment variables\n");
306            Ok(creds)
307        }
308        Err(e) => {
309            eprintln!("✗ Failed to load credentials: {}", e);
310            eprintln!("\nPlease either:");
311            eprintln!("  1. Authenticate with Salesforce CLI: sf org login web");
312            eprintln!("  2. Set environment variables: SF_INSTANCE_URL, SF_ACCESS_TOKEN");
313            Err(e.into())
314        }
315    }
316}
Source

pub async fn from_sfdx_alias( alias_or_username: &str, ) -> Result<SalesforceCredentials, Error>

Load credentials from SFDX CLI using an org alias or username.

Requires the sf CLI to be installed and the org to be authenticated.

Examples found in repository?
examples/bulk_operations.rs (line 285)
284async fn get_credentials() -> Result<SalesforceCredentials, Box<dyn std::error::Error>> {
285    if let Ok(creds) = SalesforceCredentials::from_sfdx_alias("default").await {
286        println!("✓ Using credentials from Salesforce CLI\n");
287        return Ok(creds);
288    }
289
290    match SalesforceCredentials::from_env() {
291        Ok(creds) => {
292            println!("✓ Using credentials from environment variables\n");
293            Ok(creds)
294        }
295        Err(e) => {
296            eprintln!("✗ Failed to load credentials: {}", e);
297            eprintln!("\nPlease either:");
298            eprintln!("  1. Authenticate with Salesforce CLI: sf org login web");
299            eprintln!("  2. Set environment variables: SF_INSTANCE_URL, SF_ACCESS_TOKEN");
300            Err(e.into())
301        }
302    }
303}
More examples
Hide additional examples
examples/error_handling.rs (line 313)
312async fn get_credentials() -> Result<SalesforceCredentials, Box<dyn std::error::Error>> {
313    if let Ok(creds) = SalesforceCredentials::from_sfdx_alias("default").await {
314        println!("✓ Using credentials from Salesforce CLI\n");
315        return Ok(creds);
316    }
317
318    match SalesforceCredentials::from_env() {
319        Ok(creds) => {
320            println!("✓ Using credentials from environment variables\n");
321            Ok(creds)
322        }
323        Err(e) => {
324            eprintln!("✗ Failed to load credentials: {}", e);
325            eprintln!("\nPlease either:");
326            eprintln!("  1. Authenticate with Salesforce CLI: sf org login web");
327            eprintln!("  2. Set environment variables: SF_INSTANCE_URL, SF_ACCESS_TOKEN");
328            Err(e.into())
329        }
330    }
331}
examples/queries.rs (line 427)
426async fn get_credentials() -> Result<SalesforceCredentials, Box<dyn std::error::Error>> {
427    if let Ok(creds) = SalesforceCredentials::from_sfdx_alias("default").await {
428        println!("✓ Using credentials from Salesforce CLI\n");
429        return Ok(creds);
430    }
431
432    match SalesforceCredentials::from_env() {
433        Ok(creds) => {
434            println!("✓ Using credentials from environment variables\n");
435            Ok(creds)
436        }
437        Err(e) => {
438            eprintln!("✗ Failed to load credentials: {}", e);
439            eprintln!("\nPlease either:");
440            eprintln!("  1. Authenticate with Salesforce CLI: sf org login web");
441            eprintln!("  2. Set environment variables: SF_INSTANCE_URL, SF_ACCESS_TOKEN");
442            Err(e.into())
443        }
444    }
445}
examples/basic_auth.rs (line 73)
68async fn example_from_sfdx() -> Result<(), Box<dyn std::error::Error>> {
69    println!("Example 2: Load from Salesforce CLI");
70    println!("------------------------------------");
71
72    // Try to load from default org
73    match SalesforceCredentials::from_sfdx_alias("default").await {
74        Ok(creds) => {
75            println!("✓ Loaded credentials from SFDX CLI");
76            println!("  Instance URL: {}", creds.instance_url());
77            println!("  API Version: {}", creds.api_version());
78        }
79        Err(e) => {
80            println!("✗ Failed to load from SFDX: {}", e);
81            println!("  Tip: Run 'sf org login web' or 'sf org login jwt'");
82            println!("  Or specify an alias: SalesforceCredentials::from_sfdx_alias(\"my-org\")");
83        }
84    }
85
86    println!();
87    Ok(())
88}
examples/rest_crud.rs (line 297)
295async fn get_credentials() -> Result<SalesforceCredentials, Box<dyn std::error::Error>> {
296    // Try SFDX first
297    if let Ok(creds) = SalesforceCredentials::from_sfdx_alias("default").await {
298        println!("✓ Using credentials from Salesforce CLI\n");
299        return Ok(creds);
300    }
301
302    // Fall back to environment variables
303    match SalesforceCredentials::from_env() {
304        Ok(creds) => {
305            println!("✓ Using credentials from environment variables\n");
306            Ok(creds)
307        }
308        Err(e) => {
309            eprintln!("✗ Failed to load credentials: {}", e);
310            eprintln!("\nPlease either:");
311            eprintln!("  1. Authenticate with Salesforce CLI: sf org login web");
312            eprintln!("  2. Set environment variables: SF_INSTANCE_URL, SF_ACCESS_TOKEN");
313            Err(e.into())
314        }
315    }
316}
Source

pub async fn from_sfdx_auth_url( auth_url: &str, ) -> Result<SalesforceCredentials, Error>

Load credentials from an SFDX auth URL.

The SFDX auth URL format is:

  • force://<client_id>:<client_secret>:<refresh_token>@<instance_url>
  • force://<client_id>::<refresh_token>@<instance_url> (empty client_secret)
  • force://<client_id>:<client_secret>:<refresh_token>:<username>@<instance_url> (with username)

The client_secret can be empty (indicated by ::) for the default Salesforce CLI connected app. The username field is optional.

This method will parse the auth URL and use the refresh token to obtain an access token from Salesforce.

§Example
let auth_url = std::env::var("SF_AUTH_URL")?;
let creds = SalesforceCredentials::from_sfdx_auth_url(&auth_url).await?;
Examples found in repository?
examples/test_sf_auth_url.rs (line 13)
8async fn main() {
9    let auth_url = std::env::var("SF_AUTH_URL").expect("SF_AUTH_URL must be set");
10
11    println!("Testing SF_AUTH_URL authentication...");
12
13    match SalesforceCredentials::from_sfdx_auth_url(&auth_url).await {
14        Ok(creds) => {
15            println!("✓ Successfully authenticated!");
16            println!("Instance URL: {}", creds.instance_url());
17            println!("API Version: {}", creds.api_version());
18            println!("Access token length: {}", creds.access_token().len());
19        }
20        Err(e) => {
21            eprintln!("✗ Authentication failed: {:?}", e);
22            eprintln!("\nError details: {}", e);
23            std::process::exit(1);
24        }
25    }
26}
Source

pub fn with_api_version( self, version: impl Into<String>, ) -> SalesforceCredentials

Change the API version.

Source

pub fn rest_api_url(&self) -> String

Get the base REST API URL for this org.

Examples found in repository?
examples/basic_auth.rs (line 129)
93async fn example_oauth_refresh() -> Result<(), Box<dyn std::error::Error>> {
94    println!("Example 3: OAuth 2.0 Refresh Token");
95    println!("-----------------------------------");
96
97    // Configuration from environment or hardcoded for example
98    let consumer_key =
99        std::env::var("SF_CONSUMER_KEY").unwrap_or_else(|_| "your_consumer_key".to_string());
100    let consumer_secret = std::env::var("SF_CONSUMER_SECRET").ok();
101    let refresh_token =
102        std::env::var("SF_REFRESH_TOKEN").unwrap_or_else(|_| "your_refresh_token".to_string());
103
104    if consumer_key == "your_consumer_key" {
105        println!("✗ OAuth not configured");
106        println!("  Tip: Set SF_CONSUMER_KEY and SF_REFRESH_TOKEN");
107        println!();
108        return Ok(());
109    }
110
111    let mut config = OAuthConfig::new(consumer_key);
112    if let Some(secret) = consumer_secret {
113        config = config.with_secret(secret);
114    }
115
116    let oauth = OAuthClient::new(config);
117
118    match oauth
119        .refresh_token(&refresh_token, "https://login.salesforce.com")
120        .await
121    {
122        Ok(token_response) => {
123            println!("✓ Successfully refreshed access token");
124            println!("  Instance URL: {}", token_response.instance_url);
125            println!("  Token Type: {:?}", token_response.token_type);
126
127            // Convert to credentials
128            let creds = token_response.to_credentials("62.0");
129            println!("  API URL: {}", creds.rest_api_url());
130        }
131        Err(e) => {
132            println!("✗ Failed to refresh token: {}", e);
133        }
134    }
135
136    println!();
137    Ok(())
138}
Source

pub fn tooling_api_url(&self) -> String

Get the Tooling API URL for this org.

Source

pub fn metadata_api_url(&self) -> String

Get the Metadata API URL for this org.

Source

pub fn bulk_api_url(&self) -> String

Get the Bulk API 2.0 URL for this org.

Trait Implementations§

Source§

impl Clone for SalesforceCredentials

Source§

fn clone(&self) -> SalesforceCredentials

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Credentials for SalesforceCredentials

Source§

fn instance_url(&self) -> &str

Get the Salesforce instance URL.
Source§

fn access_token(&self) -> &str

Get the access token.
Source§

fn api_version(&self) -> &str

Get the API version (e.g., “62.0”).
Source§

fn is_valid(&self) -> bool

Returns true if the credentials appear to be valid (non-empty).
Source§

impl Debug for SalesforceCredentials

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more