Authenticating Salesforce Request In .NET

Published on
-
2 min read

My custom Salesforce library that I readily use for any Salesforce integrations within my native .NET applications consists of a combination of both handwritten code as well as utilsing the functionality present within the Force.com Toolkit. Even though the Force.com Toolkit does pretty much everything you need for day to day activities like basic read and write interactions. When it comes to anything more, a custom approach is required.

I have created a AuthenticationResponse class that contains two methods so I could easily interchange between different authentication processes depending on my needs:

  • Rest - Retrieves access token to Salesforce environment in a traditional REST approach.
  • ForceCom - Retrieves authentication details when API calls using Force.com toolkit is used.
public class AuthenticationResponse
{
    /// <summary>
    /// Retrieves access token to Salesforce environment in a traditional REST approach.
    /// </summary>
    /// <returns></returns>
    public static async Task<Authentication> Rest()
    {
        HttpClient authClient = new HttpClient();
            
        // Set required values to be posted.
        HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    {"grant_type","password"},
                    {"client_id", SalesforceConfig.ConsumerKey},
                    {"client_secret", SalesforceConfig.ConsumerSecret},
                    {"username", SalesforceConfig.Username},
                    {"password", SalesforceConfig.LoginPassword}
                }
        );
            
        HttpResponseMessage message = await authClient.PostAsync($"{SalesforceConfig.PlatformUrl}services/oauth2/token", content);

        string responseString = await message.Content.ReadAsStringAsync();

        JObject obj = JObject.Parse(responseString);

        return new Authentication
        {
            AccessToken = obj["access_token"].ToString(),
            InstanceUrl = obj["instance_url"].ToString()
        };
    }

    /// <summary>
    /// Retrieves authentication details when API calls using Force.com toolkit is used.
    /// </summary>
    /// <returns></returns>
    public static async Task<ForceClient> ForceCom()
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        AuthenticationClient auth = new AuthenticationClient();

        await auth.UsernamePasswordAsync(SalesforceConfig.ConsumerKey, SalesforceConfig.ConsumerSecret, SalesforceConfig.Username, SalesforceConfig.LoginPassword, $"{SalesforceConfig.PlatformUrl}services/oauth2/token");

        ForceClient client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

        return client;
    }
}

All configuration settings such as the consumer key, consumer secret, username and password are being read from the web.config via a "SalesforceConfig" class. But these can be replaced by calling directly from your own app settings. Both methods return the access token required for querying a Salesforce platform.

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself.