Search code examples
c#asp.net-mvcasp.net-web-apiaccess-token

Asp.net Web Api 2 - how to get access_token from C# code


I am preparing a C# Api for my website. When I call the following code to login and get the access token, response.IsSuccessStatusCode is ok (200), but I could not find any access_token from the response. I assume the access token comes through response body, but could not find a proper function to get the response body.

var token = new Dictionary<string, string> { {"grant_type", "password"}, {"username", "[email protected]"}, 
{"password", "OOKKUUc564$"},};

var tknModel = new FormUrlEncodedContent(token);

var resp = await client.PostAsync("http://parkatstreet.com/Token", tknModel);
if (response.IsSuccessStatusCode)
{
    string responseStream = response.Headers.ToString();
}

The response I am getting is:

{StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Pragma: no-cache
X-SourceFiles: =?UTF-8?B?QzpcRGV2ZWxvcG1lbnRcUGF5cm9sbEFwaVxEYml0UGF5cm9sbEFwaVxEYml0UGF5cm9sbEFwaVxUb2tlbg==?= Cache-Control: no-cache Date: Thu, 24 Sep 2015 05:19:10 GMT
Set-Cookie: .AspNet.Cookies=lgQKnoQzwpUbpE9PpVm9L71rlBEBwG_oA4VT89oowNoynkdpHRfGj6Lt92XJ5N1Pnmfv_FUQ07EVuLOLpjiuLtnoqOE2SqAFvXr7tMQmoXlU-pvf8KwkTx6Fl_TyC-VrCPOoOcxEAolBcN3oHXHYcjYPaqmZpQA-mQqcjwxIumXd6eVEHfEZtRj3EiVLS0schzD9TG8IcPq3JkzEQpqu_srEBKbJQ8zIJX6TCfkFK3cvGGJ-6cbV8lIJcPke8ahnc_icDkPKnlfzZZEEZEzeamYX3u1g1R50bj-y01T0JXQLyqGK-EpzjiLwqeO5yv1-yJ_1GQrqv46lomu51WTY_oMIXvGTNEU8wurJtN2XdpBLKg1X79VQxqunniKpYGtYN1wq-sl-RPiFLz9Cnh21yD1ogSNJoWEutyOP3lpCvZp50cAktDqB-swG92_a8f6OPzFHSG0yUq01Ro1YFJNBljP5eWT8r9wGqP1ZlDHLAmQ; path=/; HttpOnly Server: Microsoft-IIS/10.0 X-Powered-By: ASP.NET Content-Length: 688 Content-Type: application/json; charset=UTF-8
Expires: -1 }}

And the response I expect is:

{ "access_token": "4b-KAhg7QNMyHNVXFBUFBq5NJvlw7_JmaXZl1SDLIi6sMl5kTh8EfnvNTNa5iUwQuiNSk2Il6nUxheAJ64rroYYF-woWcQ9l8J8g56IuCApUNJWzD31eyJrOBI2yzZcTFY8X0GqpidYhZNvTHsn4PNwOZAHAebBK64yMstb9-66kdgp-vSgvCvH1tA45drlWVuNsjmsX6EHg5WlDFJsPhnDL7Lz4sSYxtFF8ipZvAEoxJ-dGsQHRsIAygY934nrLdYP7saDCAAqlzvUoWspYIO2B9kyyzoYREjb3Y9ik8MEmuGZgk-hzAWkTRMh51tUn0wknMPVsDve_OYdX9qZlMoxDEXJjGhPmxMKd_o2AdGkPU31OTW6Y3JkQZVdTTHqUuCWMTWctkImvIpSRlpwfc71qRltbp1wy7SjHQdpeYC8ZBcjO-B6NImkxjM_yb2BVKM8TrXeqdYrRcKBer6RjpgMCwlha9oH8_yyFNqbw-U1YcrKLvIfJPqjJ45K37bkn", "token_type": "bearer", "expires_in": 1209599, "userName": "[email protected]", ".issued": "Thu, 24 Sep 2015 04:45:59 GMT", ".expires": "Thu, 08 Oct 2015 04:45:59 GMT" }


Solution

  • You can create a new Console Application and use the following code:

    namespace APIClientConsole
    {
        class Program
        {
            static void Main(string[] args)
            {
                RunAsync().Wait();
            }
    
            static async Task RunAsync()
            {
                using (var client = new HttpClient())
                {
                    // TODO - Send HTTP requests              
                    client.BaseAddress = new Uri("http://localhost:24780/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                
                    // HTTP POST                
                    var body = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>("grant_type", "password"),
                        new KeyValuePair<string, string>("username", "bnk"),
                        new KeyValuePair<string, string>("password", "bnk123")                    
                    };
                    var content = new FormUrlEncodedContent(body);
                    HttpResponseMessage response = await client.PostAsync("token", content);
                    if (response.IsSuccessStatusCode)
                    {
                        string responseStream = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseStream);   
                        Console.ReadLine();                 
                    }
                }
            }
        }        
    }
    

    You can read more at the following link

    Calling a Web API From a .NET Client in ASP.NET Web API 2 (C#)