Ender Aric
Ender Aric

Reputation: 257

How to get token with C# WebApi Client (Owin)

I am using Owin.Oauth for authorization. When i send this parameters with postman i can get json data from webapi. the url is http://localhost:53415/token

Headers (Key-Value)

Accept           application/json
Content-Type     application/x-www-form-urlencoded

Body

grant_type       password
username         user_1
password         123456

The result is below

{
    "access_token": "Q0G_r6iLTFk1eeZedyL4JC0Z6Q-sBwVmtSasrNm8Yb1MCscDkeLiXugKrXq236LEJK6vM8taXf9cfWhCKRTcBWrQ14x5FOFKE1oV5xdW8VKZL8LZSzsvEwzP5Rr7G4lnkakxcsbu151LkkmM_dIF3Rx9_cvk0z1TKUznm9Ke_jxKgjichd-8fmdsupmysuP00biNuT6PYZPHiMYXaON2YiCK67A1yGHb-X2GhBL6NWc",
    "token_type": "bearer",
    "expires_in": 86399
}

So i am trying to make this in C# MVC client. I created an api helper to make this and here is my tried code below.

                ApiHelper<CampaignList> _api = new ApiHelper<CampaignList>();
                JObject oJsonObject = new JObject();
                oJsonObject.Add("grant_type", "password");
                oJsonObject.Add("username", "user_1");
                oJsonObject.Add("password", "123456");
                _api.GetToken(oJsonObject);

Now in ApiHelper the code is this :

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(WebConfigurationManager.AppSettings["apiUrl"]);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
HttpResponseMessage response = client.PostAsJsonAsync("token", oJsonObject.ToString()).Result;
if (response.IsSuccessStatusCode)
   {
       ApiTokenEntity _entity = response.Content.ReadAsAsync<ApiTokenEntity>().Result;
       return _entity;
   }
   else
   {
       return null;
   }

if (response.IsSuccessStatusCode) line has returned false and i couldn't get my token to return. So i need to get token to send with header. Where do I make wrong i dk.

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

    [JsonProperty(PropertyName = "expires_in")]
    public int ExpiresIn { get; set; }

    [JsonProperty(PropertyName = "token_type")]
    public string TokenType { get; set; }

}

Upvotes: 0

Views: 3345

Answers (1)

John Velasquez
John Velasquez

Reputation: 3451

POST payload should be a query string format

You need to convert the object to something like this

grant_type=password&username=user_1&password=123456

Write a method that converts your object into a query string param

public string GetQueryString(object obj) {
  var properties = from p in obj.GetType().GetProperties()
                   where p.GetValue(obj, null) != null
                   select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj, null).ToString());

  return String.Join("&", properties.ToArray());
}

// Usage:
string queryString = GetQueryString(foo);

Reference here.

Since its a string change the PostAsJsonAsync to PostAsync

So your implementation should be like this

string result = GetQueryString(oJsonObject);
StringContent payload = new StringContent(result);
HttpResponseMessage response = client.PostAsync("token", payload).Result;

Upvotes: 1

Related Questions