1
votes

I am trying to get access token using OAuth for a salesforce account.I have Consumer Key and Consumer Secret Below is my code. But it throws an exception when it calls the method UsernamePasswordAsync. Please help me around this issue.

private static async Task RunSample()
        {
            try
            {
                var auth = new AuthenticationClient();
                // Authenticate with Salesforce
                Console.WriteLine("Authenticating with Salesforce");
                var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                    ? "https://login.salesforce.com/services/oauth2/token "
                    : "https://test.salesforce.com/services/oauth2/token";

                await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);
                Console.WriteLine("Connected to Salesforce");
                var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
                // retrieve all accounts
                Console.WriteLine("Get Accounts");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }

EDIT: The exception I am getting is Exception: authentication failure Error:Salesforce.Common.Models.Error.InvalidGrant Stack Trace: at Salesforce.Common.AuthenticationClient.d__1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at SalesForceAuthSample.Program.d__7.MoveNext() in C:\Users\Pankaj Dalvi\Documents\Visual Studio 2015\Projects\MVP\SalesForceAuthSample\SalesForceAuthSample\Program.cs:line 65

1
Add the exception to your post. - jegtugado
We won't be able to help you without the content of the exception.. - dbraillon
I get the same error, what was the solution? - Philippe

1 Answers

0
votes

As long as you are sure you have all of your credentials correct - the next item that I would check is your OAuth Policy listed in the Edit Menu of your Connected App. For the username-password OAuth flow, I believe this needs to be set to All users may self-authorize.

The other option, Admin approved users are pre-authorized doesn't seem to make sense in the username-password flow, e.g. there is no approval step from the user when using the username-password flow. The other two flow types, webserver flow and user agent flow, do have an approval step. Salesforce's Edit Connected App Behavior has more details.