Friday, March 20, 2015

Getting an OAuth Bearer Token from a .NET Client

If you have read this article (, you probably already know how to call ASP.NET Web API from a .NET Client.

However, you may not be sure how to get an OAuth Bearer Token from a .NET Client in order to be able to use it throughout your Client Application.

Well, fortunately, it is actually relatively simple to accomplish this!

You can simply use an HttpClient Post to make the appropriate call to the OAuth Token Service:
public BearerToken GetOAuthToken()
    BearerToken token = null;
    var pairs = new List<KeyValuePair<string, string>>
        new KeyValuePair<string, string>("username", "myusername"),
        new KeyValuePair<string, string>("password", "myusername"),
        new KeyValuePair<string, string>("grant_type", "password")
    var content = new FormUrlEncodedContent(pairs);
    using (var client = new HttpClient())
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        // New code:
        HttpResponseMessage response = client.PostAsync(new Uri("http://localhost:9000/Token"), content).Result;
        if (response.IsSuccessStatusCode)
            token = response.Content.ReadAsAsync<BearerToken>().Result;
    return token;

The code for the BearerToken class is as follows:


public class BearerToken
    public string access_token { get; set; }
    public string expires_in { get; set; }
    public string token_type { get; set; }


Therefore, your call to your method will look like this:


var token = client.GetOAuthToken();
string access_token = token.access_token;

If you then want to send the Bearer Token along in a subsequent ASP.NET Web API Request, you just have to make sure that you set the Authorization Header like so:

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", OAuthToken);

That is all there is to it!!

No comments:

Post a Comment