72

I am trying to perform a Post to my WebAPI from a c# WPF desktop app.

No matter what I do, I get

{"error":"unsupported_grant_type"}

This is what I've tried (and I've tried everything I could find):

Also dev web api currently active for testing: http://studiodev.biz/

base http client object:

var client = new HttpClient()
client.BaseAddress = new Uri("http://studiodev.biz/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));

with the following send methods:

var response = await client.PostAsJsonAsync("token", "{'grant_type'='password'&'username'='username'&'password'='password'");
var response = await client.PostAsJsonAsync("token", "grant_type=password&username=username&password=password");

After that failed, I did some googling and tried:

LoginModel data = new LoginModel(username, password);
string json = JsonConvert.SerializeObject(data);
await client.PostAsync("token", new JsonContent(json));

same result, so I tried:

req.Content = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded");
await client.SendAsync(req).ContinueWith(respTask =>
{
 Application.Current.Dispatcher.Invoke(new Action(() => { label.Content = respTask.Result.ToString(); }));
});

Note: I can make a successful call with Chrome.

Update Fiddler Result

enter image description here

Could someone please help me make a successful call to the above web api... Please let me know if I can help clarify. Thanks!!

OverMars
  • 1,077
  • 3
  • 16
  • 33

8 Answers8

161

The default implementation of OAuthAuthorizationServerHandler only accepts form encoding (i.e. application/x-www-form-urlencoded) and not JSON encoding (application/JSON).

Your request's ContentType should be application/x-www-form-urlencoded and pass the data in the body as:

grant_type=password&username=Alice&password=password123

i.e. not in JSON format.

The chrome example above works because it is not passing data as JSON. You only need this for getting a token; for other methods of your API you can use JSON.

This kind of problem is also discussed here.

Community
  • 1
  • 1
M. Ali Iftikhar
  • 3,125
  • 2
  • 26
  • 36
17

1) Note the URL: "localhost:55828/token" (not "localhost:55828/API/token")

2) Note the request data. Its not in json format, its just plain data without double quotes. "userName=xxx@gmail.com&password=Test123$&grant_type=password"

3) Note the content type. Content-Type: 'application/x-www-form-urlencoded' (not Content-Type: 'application/json')

4) When you use javascript to make post request, you may use following:

$http.post("localhost:55828/token", 
    "userName=" + encodeURIComponent(email) +
        "&password=" + encodeURIComponent(password) +
        "&grant_type=password",
    {headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
).success(function (data) {//...

See screenshots below from Postman:

Postman Request

Postman Request Header

Chirag
  • 1,683
  • 2
  • 17
  • 26
15

Here is a working example I used to make this request of my local Web API application running on port 43305 using SSL. I put the project on GitHub as well. https://github.com/casmer/WebAPI-getauthtoken

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http;
using System.Web;

namespace GetAccessTokenSample
{
  class Program
  {
    private static string baseUrl = "https://localhost:44305";

    static void Main(string[] args)
    {

      Console.WriteLine("Enter Username: ");
      string username= Console.ReadLine();
      Console.WriteLine("Enter Password: ");
      string password = Console.ReadLine();

      LoginTokenResult accessToken = GetLoginToken(username,password);
      if (accessToken.AccessToken != null)
      {
        Console.WriteLine(accessToken);
      }
      else
      {
        Console.WriteLine("Error Occurred:{0}, {1}", accessToken.Error, accessToken.ErrorDescription);
      }

    }


    private static LoginTokenResult GetLoginToken(string username, string password)
    {

      HttpClient client = new HttpClient();
      client.BaseAddress = new Uri(baseUrl);
      //TokenRequestViewModel tokenRequest = new TokenRequestViewModel() { 
      //password=userInfo.Password, username=userInfo.UserName};
      HttpResponseMessage response =
        client.PostAsync("Token",
          new StringContent(string.Format("grant_type=password&username={0}&password={1}",
            HttpUtility.UrlEncode(username),
            HttpUtility.UrlEncode(password)), Encoding.UTF8,
            "application/x-www-form-urlencoded")).Result;

      string resultJSON = response.Content.ReadAsStringAsync().Result;
      LoginTokenResult result = JsonConvert.DeserializeObject<LoginTokenResult>(resultJSON);

      return result;
    }

    public class LoginTokenResult
    {
      public override string ToString()
      {
        return AccessToken;
      }

      [JsonProperty(PropertyName = "access_token")]
      public string AccessToken { get; set; }

      [JsonProperty(PropertyName = "error")]
      public string Error { get; set; }

      [JsonProperty(PropertyName = "error_description")]
      public string ErrorDescription { get; set; }

    }

  }
}
Casey Gregoire
  • 181
  • 1
  • 7
9

If you are using RestSharp, you need to make the request like this:

public static U PostLogin<U>(string url, Authentication obj)
            where U : new()
{
            RestClient client = new RestClient();
            client.BaseUrl = new Uri(host + url);
            var request = new RestRequest(Method.POST);
            string encodedBody = string.Format("grant_type=password&username={0}&password={1}",
                obj.username,obj.password);
            request.AddParameter("application/x-www-form-urlencoded", encodedBody, ParameterType.RequestBody);
            request.AddParameter("Content-Type", "application/x-www-form-urlencoded", ParameterType.HttpHeader);
            var response = client.Execute<U>(request);
            
            return response.Data;
}
  • 1
    This was helpful, thanks! For those looking to get a token for later I just copied this answer and added this line before the client.Execute call: request.Resource = "Token"; – Chris Nov 12 '18 at 17:47
1

Had same issues but only resolved mine over secured HTTP for the token URL. See sample httpclient code. Ordinary HTTP just stop working after server maintenance

var apiUrl = "https://appdomain.com/token"
var client = new HttpClient();    
client.Timeout = new TimeSpan(1, 0, 0);
            var loginData = new Dictionary<string, string>
                {
                    {"UserName", model.UserName},
                    {"Password", model.Password},
                    {"grant_type", "password"}
                };
            var content = new FormUrlEncodedContent(loginData);
            var response = client.PostAsync(apiUrl, content).Result;
Afis
  • 32
  • 1
  • 5
0

it my case, i m forget install install package Token.JWT, so you need install too in your project. Install-Package System.IdentityModel.Tokens.Jwt -Version 6.7.1

AgungCode.Com
  • 677
  • 6
  • 9
0

It may be the cause of protocol it's required https://

EX : https://localhost:port/oauth/token

Raviteja V
  • 454
  • 5
  • 11
0
jQuery.ajax({

    "method": "post",
    "url": "https://localhost:44324/token",
    **"contentType": "application/x-www-form-urlencoded",**
    "data": {
      "Grant_type": "password",
      "Username": $('#txtEmail').val(),
      "Password": $('#txtPassword').val()
    }
  })
    .done(function (data) { console.log(data); })
    .fail(function (data) { console.log(data); })

//In Global.asax.cs (MVC WebApi 2)

protected void Application_BeginRequest()

    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        
    }

enter image description here

T.S.
  • 18,195
  • 11
  • 58
  • 78
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 29 '22 at 02:31