Suburbanpsyco6
Suburbanpsyco6

Reputation: 67

Salesforce Rest API OAuth - Bad Response Error

Any help here is appreciated. Im simply trying to do the basic call to the Oauth Username-Password Flow. Its giving me a Bad Request (400) Error right when I try to call GetResponse().

        string sessionId = String.Empty;

        string url = ConfigurationManager.AppSettings["SfdcLoginUrl"].ToString();

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://test.salesforce.com/services/oauth2/token");
        request.Method = "POST";
        request.ContentType = "application/json";

        StringBuilder sb = new StringBuilder();
        sb.Append("grant_type=password&");
        sb.Append("client_id=" + ConfigurationManager.AppSettings["ClientId"].ToString() + "&");
        sb.Append("client_secret=" + ConfigurationManager.AppSettings["ClientSecret"].ToString() + "&");
        sb.Append("username=" + HttpUtility.UrlPathEncode(username) + "&");
        sb.Append("password=" + HttpUtility.UrlPathEncode(password));

        System.Text.ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] bytes = encoding.GetBytes(sb.ToString());

        request.ContentLength = bytes.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
        }

        WebResponse response = request.GetResponse();

        StreamReader reader = new StreamReader(response.GetResponseStream());
        sessionId = reader.ReadToEnd();

Upvotes: 0

Views: 3178

Answers (2)

Chen Qing
Chen Qing

Reputation: 11

Just to add a link back to offical doc, https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_username_password_oauth_flow.htm

"You must append the user’s security token to their password A security token is an automatically-generated key from Salesforce. For example, if a user's password is mypassword, and their security token is XXXXXXXXXX, then the value provided for this parmeter must be mypasswordXXXXXXXXXX."

Upvotes: 1

Gimhan
Gimhan

Reputation: 62

password should be password+security token if not your ip address white listed in salesforce remote access area

Upvotes: 0

Related Questions