ABJ
ABJ

Reputation: 309

Sales Force Authentication from ASP.Net Web Page C#

I am using OAuth 2.0 to authenticate my website with sales force. I downloaded and ran the Java sample code and it worked fine. Now I need to do the same from a ASP.Net web page but it does not seem to work. When I do the final POST to get the access token it gives me an error System.Net.WebException: The remote server returned an error: (400) Bad Request.

I am using the same httppost method as mentioned in this link here. For details the code that does the post is below.

public partial class Authenticate2 : System.Web.UI.Page
{
    private string tokenUrl;
    protected void Page_Load(object sender, EventArgs e)
    {
        Logger.LogInfoMessage("I am Authenticate 2");
        string code = Request["code"];
        Logger.LogInfoMessage("Code is: " + code);
        string parameters = "code=" + code
            + "&grant_type=authorization_code"
            + "&client_id=" + Authenticate.CONSUMER_KEY
            + "&client_secret=" + Authenticate.CONSUMER_SECRET
            + "&redirect_uri" + Authenticate.REDIRECT_URL;
        string result = HttpPost(tokenUrl, parameters);
        Logger.LogInfoMessage(result);
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        tokenUrl = Authenticate.ENVIRONMENT + "/services/oauth2/token";
    }
    public string HttpPost(string URI, string Parameters)
    {
        System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
        req.ContentType = "application/x-www-form-urlencoded";
        req.Method = "POST";

        // Add parameters to post
        byte[] data = System.Text.Encoding.ASCII.GetBytes(Parameters);
        req.ContentLength = data.Length;
        System.IO.Stream os = req.GetRequestStream();
        os.Write(data, 0, data.Length);
        os.Close();

        // Do the post and get the response.
        System.Net.WebResponse resp = req.GetResponse();
        if (resp == null) return null;
        System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
        return sr.ReadToEnd().Trim();
    }
}

The authenticate class simply does the redirect as per this:

public partial class Authenticate : System.Web.UI.Page
{
    public const string CONSUMER_KEY = "XXX";
    public const string CONSUMER_SECRET = "XXX";
    public  const string REDIRECT_URL = "https://localhost/authenticate2.aspx";
    public  const string ENVIRONMENT = "https://test.salesforce.com";

    public  const string ACCESS_TOKEN = "ACCESS_TOKEN";
    public  const string INSTANCE_URL = "INSTANCE_URL";
    public  const string INVOICE_ID = "invoiceId";

    private string authenticateUrl = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        Logger.LogInfoMessage("I am in Authenticate");
        string accessToken = (string)Session[ACCESS_TOKEN];
        Logger.LogInfoMessage("Access Token is:" + accessToken);
        if (accessToken == null)
        {
            Logger.LogInfoMessage("Redirecting to:" + authenticateUrl);
            Response.Redirect(authenticateUrl);
            return;
        }
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        authenticateUrl = ENVIRONMENT
                + "/services/oauth2/authorize?response_type=code&client_id="
                + CONSUMER_KEY + "&redirect_uri="
                + HttpUtility.UrlEncode(REDIRECT_URL, System.Text.Encoding.UTF8);
    }
}

The screen shot of the error I get is as per follows:

The Screen Shot of the error

Upvotes: 1

Views: 2373

Answers (3)

Pallavi Agarwal
Pallavi Agarwal

Reputation: 19

There is javascript version of oAuth implementation of Salesforce API, but you can use it to understand the authentication flow: https://www.youtube.com/watch?v=ULWBdjJx1Ss

The video describes STEP BY STEP process required to obtain token and use it to get data.

Upvotes: 0

JWiley
JWiley

Reputation: 3219

Your HTTPPost params are constructed incorrectly, which is why the request is turned back with "bad request":

string parameters = "code=" + code
            + "&grant_type=authorization_code"
            + "&client_id=" + Authenticate.CONSUMER_KEY
            + "&client_secret=" + Authenticate.CONSUMER_SECRET
            + "&redirect_uri" + Authenticate.REDIRECT_URL;

You are missing the "=" here: + "&redirect_uri=" + Authenticate.REDIRECT_URL;

Upvotes: 0

superfell
superfell

Reputation: 19040

When you build the parameters string you need to URLencode each of the parameter values. You can also catch the WebException and read the response body which'll also have more info on the problem.

Upvotes: 2

Related Questions