-1

I am trying to post values to server authenticate method http://*/Token . From my C# client i get 400 Bad request error. While it works fine in jquery.

jQuery Code:

$( "#post2").click(function() {
    var Email=$('#Email').val();
    var Password=$('#Password').val();
    $.ajax({
        type:"Post",                    
        url: "http://***/Token",
        data:{
                "grant_type": "password",
                "username": Email,
                "password": Password
            },
        success: function(msg) 
        {
            user=msg["access_token"];
            console.log(JSON.stringify(msg));
        }
    });
});

C# code

string email = "***@gmail.com";
string password = "***";
var tok = new TokenModel{grant_type = "password", username = email, password = password};
var s = JsonConvert.SerializeObject (tok);

var request = HttpWebRequest.Create (string.Format (@"http://***/Token", ""));
request.ContentType = "application/json";
request.Method = "POST";
using (var writer = new StreamWriter (request.GetRequestStream ())) {
    writer.Write (s);
}

using (HttpWebResponse responses = request.GetResponse () as HttpWebResponse) {

}

I also tried by creating local json

var x = new
{
    grant_type = "password",
    username = "****@gmail.com",
    password = "***"
};

But still the same error.

Is there anything i should do extra for making this call to server from C# client?

Please help, Thanks

Pragmateek
  • 13,174
  • 9
  • 74
  • 108
Erma Isabel
  • 2,167
  • 8
  • 34
  • 64

2 Answers2

0

jQuery's ajax()'s data parameter doesn't contain a json object, but an object which later gets transformed into the post arguments (such as ?var1=foo&var2=bar).

So try:

using (WebClient client = new WebClient())
{
    byte[] response = client.UploadValues("http://***/Token", new NameValueCollection()
    {
        { "grant_type", "password" },
        { "username", "****@gmail.com" },
        { "password", "*****" }
    });
}
nozzleman
  • 9,529
  • 4
  • 37
  • 58
  • I don't know. I couldn't find anything :-( – Erma Isabel May 27 '14 at 11:09
  • I have got this error when exception response is consoled, {"error":"unsupported_grant_type"} – Erma Isabel May 27 '14 at 12:12
  • i gueass then we cant help you. Bad Request is often used by APIs for cases where parameters where missing of having bad values. You should check the Documentation of the service you want to call, as the error message seems to state that `"password"` is not a valid value for the `grant_type` parameter – nozzleman May 27 '14 at 12:40
  • Something else is wrong. Then how it works in jquery? – Erma Isabel May 27 '14 at 12:48
  • does the jQuery Call happen on the same server? – nozzleman May 27 '14 at 12:58
  • try adding `client.Headers.Add("Content-Type","application/x-www-form-urlencoded");` before `client.UploadValues(..)` – nozzleman May 27 '14 at 13:06
  • im afraid im out of ideas too in this case. The last one would be to check wheather there are some unintended whitespaces somewhere in the argument. Sorry i cant help :( – nozzleman May 28 '14 at 07:07
  • on the other hand, if you are trying to call use oAuth, have a look at this http://stackoverflow.com/questions/4002847/oauth-with-verification-in-net – nozzleman May 28 '14 at 07:09
0

Solved:

    public async Task<string> Login(string username, string password)
    {

        HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}Token", "http://***.net/")));
        request.Method = "POST";

        string postString = String.Format("username={0}&password={1}&grant_type=password", HttpUtility.HtmlEncode(username), HttpUtility.HtmlEncode(password));
        byte[] bytes = Encoding.UTF8.GetBytes(postString);
        using (Stream requestStream = await request.GetRequestStreamAsync())
        {
            requestStream.Write(bytes, 0, bytes.Length);
        }

        try
        {
            HttpWebResponse httpResponse =  (HttpWebResponse)(await request.GetResponseAsync());
            string json;
            using (Stream responseStream = httpResponse.GetResponseStream())
            {
                json = new StreamReader(responseStream).ReadToEnd();
                Console.WriteLine(json);
            }
            TokenResponseModel tokenResponse = JsonConvert.DeserializeObject<TokenResponseModel>(json);
            return tokenResponse.AccessToken;
        }
        catch (Exception ex)
        {
            Console.WriteLine ("h..........." + ex);
            //throw new SecurityException("Bad ls", ex);
            return null;
        }
    }
Erma Isabel
  • 2,167
  • 8
  • 34
  • 64