Manager for Salesforce Simple Tasks – Part II – Authentication

Manager for Salesforce Simple Tasks – Part II – Authentication

In the first blog post of this series, we talked about the different models and the interface that we will implement to have a full functional Salesforce manager. In the second part of this series, we will work on the authentication process. As mentioned before, we are using the Force.com library in a dot.net core solution. So without further due lets begin.

We first need to set some configurations in the appsettings.json file which we will later describe one by one in more detail.

 "Salesforce": {
    "ClientId": "ID_FROM_APP",
    "ClientSecret": "SECRET_FROM_APP",
    "Username": "USER",
    "Password": "PASS",
    "Token": "PERSONAL_TOKEN",
    "SandboxAuthURL": "https://test.salesforce.com/services/oauth2/token",
    "ClientApiVersion": "v51.0",
    "DefaultOwner": "OWNER_ID"
  },

Client id and client secret are properties of the connected application created in order to connect with salesforce and the dot net core project. You can find it in the Setup – Platform Tools – Apps – App Manager section. Click in the down arrow of the application you want to see the details and then in view link.

Then you can see a manage consumer details button which will display the information you need. You will need admin access to see the details.

Copy and paste the key as client id and the secret and client secret

User name and password is set with the information of a Salesforce user with the corresponding permissions which can be added, deleted and modified from the Setup – Administration – Users – Users section

The security token field can be reset going to your profile and then to the settings link

Then, go to my personal information and to the option “Reset My Security Token”, click in the reset security token button which will display the new token if you do not remember the old one. Remember that this token is attached to the user name and password fields setup before.

The Sandbox Authentication URL is always the same if you are pointing to Salesforce sandbox environments. In this case the URL is https://test.salesforce.com/services/oauth2/token

The Client API Version can be set to your needs. We use the 51.0 version but it can be lower or higher.

And finally, the Default Owner id can be found in the URL bar address when you go to edit the details of the user that will be used to connect to salesforce in the Setup – Administration – Users – Users section

The owner id will be after the address query string parameter between the %2F and the %3F separators, check the red rectangle in the image above.

With all these parameters correctly set, now we can start with the authentication process. We will first, create the class Salesforce Manager implementing the interface ISalesforceManager defined in the previous blog post of this series. Keep in mind that if you are using these manager when you define the interface and implementation in your dependency injection resolver, it must be added as a transient service.

context.Services.AddTransient<ISalesforceManager, SalesforceManager>();

Then we will create several variables that we will use when we implement the rest of the manager, like the Salesforce client, a log service, default owner and a Boolean variables to check if the client is authenticated. We will also add a constructor that can get the configurations from the appsettings.json file and then as the last step in the constructor it will authenticate the manager.

public class SalesforceManager : ISalesforceManager
{
    private readonly string _defaultOwner;

    private readonly ILogService _logService;
    private ForceClient _client;

    private string _currentSalesForceError;

    private bool _isAuthenticated;

    public SalesforceManager(IConfiguration configuration, ILogService logService)
    {
        _logService = logService;
        _defaultOwner = configuration["Salesforce:DefaultOwner"];
        Authenticate(configuration);
    }
  }

The authentication method will receive the configuration parameter which can read settings from the appsettings.json file. Using all the parameters we set at the beginning of this blog post, we will use the authentication client class from the Force.com library to authenticate with Salesforce, we will need the sandbox authentication URL and the password is the concatenation of the user password plus the user token.

    public void Authenticate(IConfiguration configuration)
    {
        try
        {
            _isAuthenticated = false;

            var clientId = configuration["Salesforce:ClientId"];
            var clientSecret = configuration["Salesforce:ClientSecret"];
            var username = configuration["Salesforce:Username"];
            var password = configuration["Salesforce:Password"];
            var token = configuration["Salesforce:Token"];
            var version = configuration["Salesforce:ClientApiVersion"];
            var sandboxAuthUrl = configuration["Salesforce:SandboxAuthURL"];

            var auth = new AuthenticationClient(version);
            if (!string.IsNullOrEmpty(sandboxAuthUrl))
            {
                AsyncHelpers.RunSync(() => auth.UsernamePasswordAsync(clientId, clientSecret, username, password + token,
                    sandboxAuthUrl));
            }
            else
            {
                throw new Exception("No sandbox auth url set");
            }

            var instanceUrl = auth.InstanceUrl;
            var accessToken = auth.AccessToken;
            var apiVersion = auth.ApiVersion;

            _client = new ForceClient(instanceUrl, accessToken, apiVersion);
            _isAuthenticated = true;
        }
        catch (Exception ex)
        {
            _currentSalesForceError = ex.InnerException + "-" + ex.Message;
        }
    }

And that is it. You now have a basic Salesforce manager with the authentication process in place, with all the required fields to enable this connection and where exactly you can find those fields in Salesforce. If you have any questions or suggestions please let me know in the comments. I hope this can help someone and as always keep learning !!!

Written by:

Jorge Cardenas

Developer with several years of experience who is passionate about technology and how to solve problems through it.

View All Posts

Leave a Reply