oauth2 c# example

219 views
Skip to first unread message

Tom Thomas

unread,
Jan 16, 2015, 5:53:30 PM1/16/15
to merchantos-a...@googlegroups.com
Looking for a basic example implementing oauth2 in c# using headers.  This is code I've used for Salesforce oauth2.  

It would be great to hit the ground running with a working example....

Thanks!!!

public async Task AuthUser()
        {
            if (serviceUrl != null)
                return;

            HttpClient authClient;
            
            authClient = new HttpClient();

            HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    {"grant_type","password"},
                    {"client_id",ConsumerKey},
                    {"client_secret",ConsumerSecret},
                    {"username",Username},
                    {"password",Password}
                }
            );

            var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                   ? "https://test.salesforce.com/services/oauth2/token"
                   : "https://login.salesforce.com/services/oauth2/token";

            HttpResponseMessage message = await authClient.PostAsync(url, content).ConfigureAwait(false);

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

            if (responseString.Contains("error_description"))
            {
                Log.Error(String.Format("Salesforce Authorization failed in SalesforeceRestService with: {0}", responseString));
            }
            else
            {
                JObject obj = JObject.Parse(responseString);
                oAuthToken = (string)obj["access_token"];
                serviceUrl = (string)obj["instance_url"];
            }
        }


Then once authenticated I add it to my header for subsequent call as follows..

request.Headers.Add("Authorization", "Bearer " + oAuthToken);


Reply all
Reply to author
Forward
0 new messages