locked
Bad Request from API when requesting Authentication RRS feed

  • Question

  • User1595993364 posted

    I am using the below code:

    using (var client = new HttpClient())
                {
                    Uri url = new Uri(URL + api + param);
                    client.BaseAddress = new Uri(URL + api);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    var content = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair<string, string>("grant_type", "password"), 
                        new KeyValuePair<string, string>("username", username),
                        new KeyValuePair<string, string>("password", password)
                    });
    
                    var login = client.PostAsync(new Uri(URL + api), content).Result;
    
                    var result = login.Content.ReadAsStringAsync().Result;
    
                    Dictionary<string, string> tokenDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
    
                    string accessToken = tokenDictionary["access_token"];
    
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
    
                    HttpResponseMessage response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        Incident inc = await response.Content.ReadAsAsync<Incident>();
                        Console.WriteLine("{0}\t${1}", inc.ID, inc.Desc);
                    }
                }

    When I get the results from the client.PostAsync().Results, I get the below message:

    {StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
    {
    Transfer-Encoding: chunked
    X-Cnection: close
    Date: Wed, 24 Jun 2015 15:45:08 GMT
    Set-Cookie: JSESSIONID=;Secure; Path=/; HttpOnly
    Set-Cookie: BIGipServerpool_server=488718602.34110.0000; path=/
    Server: server
    Content-Type: application/json
    }}

    Any pointers would be greatly appreciated,

    Wednesday, June 24, 2015 11:47 AM

Answers

  • User438962230 posted

    Hi Robert,

    Are you sure the WebAPI service support OAuth2 authentication? 

    I recommend that you use Fiddler to check the request and response message, see if the request meets the criteran of the service provider. Contact the service provider for the API of the authentication. 

    If you it's your own WebAPI application, and you want to enable the Individual Accounts Authentication, please check this article for how to do it:

    Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, June 28, 2015 4:33 AM
  • User-782957977 posted

    Try like this.

    HttpClient client = new HttpClient();
                var pairs = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>( "grant_type", "password" ), 
                            new KeyValuePair<string, string>( "username", userName ), 
                            new KeyValuePair<string, string> ( "Password", password )
                        };
                var content = new FormUrlEncodedContent(pairs);
                HttpResponseMessage response = client.PostAsync("http://localhost:58745/token", content).Result;
                var result = response.Content.ReadAsStringAsync().Result;
                 Dictionary<string, string> tokenDictionary =
                    JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
                string token =  tokenDictionary["access_token"];

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, June 28, 2015 9:54 AM
  • User-138691462 posted
    400 Http bad request general means json parameters are invalid if your web API using POST with application/json media Type.
    Check the code of the parameters:
    var content = new FormUrlEncodedContent(new[]
    {
    new KeyValuePair<string, string>("grant_type", "password"),
    new KeyValuePair<string, string>("username", username),
    new KeyValuePair<string, string>("password", password)
    });
    Or just use JsonConvert.SerializeObject to serialize your parameters.
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, June 28, 2015 10:13 PM

All replies

  • User1779161005 posted

    Oh, sorry -- You're already doing that. I was the app/json and replied too fast.

    Wednesday, June 24, 2015 12:45 PM
  • User1779161005 posted

    Perhaps try using the OAuth2Client library instead to see if it's your code, or the server's code:

    http://leastprivilege.com/2013/11/23/thinktecture-identitymodel-client-v1-0/

    Wednesday, June 24, 2015 12:46 PM
  • User438962230 posted

    Hi Robert,

    Are you sure the WebAPI service support OAuth2 authentication? 

    I recommend that you use Fiddler to check the request and response message, see if the request meets the criteran of the service provider. Contact the service provider for the API of the authentication. 

    If you it's your own WebAPI application, and you want to enable the Individual Accounts Authentication, please check this article for how to do it:

    Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, June 28, 2015 4:33 AM
  • User-782957977 posted

    Try like this.

    HttpClient client = new HttpClient();
                var pairs = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>( "grant_type", "password" ), 
                            new KeyValuePair<string, string>( "username", userName ), 
                            new KeyValuePair<string, string> ( "Password", password )
                        };
                var content = new FormUrlEncodedContent(pairs);
                HttpResponseMessage response = client.PostAsync("http://localhost:58745/token", content).Result;
                var result = response.Content.ReadAsStringAsync().Result;
                 Dictionary<string, string> tokenDictionary =
                    JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
                string token =  tokenDictionary["access_token"];

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, June 28, 2015 9:54 AM
  • User-138691462 posted
    400 Http bad request general means json parameters are invalid if your web API using POST with application/json media Type.
    Check the code of the parameters:
    var content = new FormUrlEncodedContent(new[]
    {
    new KeyValuePair<string, string>("grant_type", "password"),
    new KeyValuePair<string, string>("username", username),
    new KeyValuePair<string, string>("password", password)
    });
    Or just use JsonConvert.SerializeObject to serialize your parameters.
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, June 28, 2015 10:13 PM