Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant get the asp.net Web API token using http client

I am trying to use http Client to make a call to Web API to get the token.I have one MVC app and Web API app.below is the MVC controller action I have.

[HttpPost]
public ActionResult Login()
{
    LoginModel m = new LoginModel();
    m.grant_type = "password";
    m.username = "xxx";
    m.password = "xxx1234";
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:51540/"); 
    var response = client.PostAsJsonAsync("Token", m).Result;
    response.EnsureSuccessStatusCode();
    return View();
}

But when I make the request the API responds as BAD request. I tried to add the content type as "application/json" and have confirmed using fiddler that the request is of type json.

I am able to register the user using Web API so at WebAPI side things are looking fine to me,I am using default project created by VS2013 using Individual account and haven't modified any thing on API side.

I am following this tutorial http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api and trying to use HTTP Client instead of fiddler.

I will be thankful if someone helps me

like image 358
varun Avatar asked Dec 01 '22 17:12

varun


2 Answers

TokenEndpointRequest seems doesn't support JSON yet, but you can use query string

var response = client.PostAsync("Token", new StringContent("grant_type=password&username=xxx&password=xxx1234", Encoding.UTF8)).Result;
like image 174
E-Cheng Liu Avatar answered Dec 04 '22 05:12

E-Cheng Liu


Here's my code from the answer & comment above

using (var client = new HttpClient{ BaseAddress = new Uri(BaseAddress) })
{
    var token = client.PostAsync("Token", 
        new FormUrlEncodedContent(new []
        {
            new KeyValuePair<string,string>("grant_type","password"),
            new KeyValuePair<string,string>("username",user.UserName),
            new KeyValuePair<string,string>("password","P@ssW@rd")
        })).Result.Content.ReadAsAsync<AuthenticationToken>().Result;

    client.DefaultRequestHeaders.Authorization = 
           new AuthenticationHeaderValue(token.token_type, token.access_token);

    // actual requests from your api follow here . . .
}

created an AuthenticationToken class for beautification purposes:

public class AuthenticationToken
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
}
like image 43
K. R. Avatar answered Dec 04 '22 05:12

K. R.