Consuming External OAuth Services using IdentityModel

Scott Brady
Scott Brady

Recently as part of my audition process to become a Pluralsight author I created a 10 minute video on ‘Consuming External OAuth Services using IdentityModel’. I’m pretty pleased with how it turned out, and luckily so were Pluralsight, so I thought I would share it for all to see.

In the video, I talk about why OAuth exists, what a basic OAuth request looks like and how we can use the IdentityModel library to help us simplify the process in .NET.

The only thing I didn't have time to fit in was a comparison between making an OAuth request yourself vs. IdentityModel. I've added this code below as I think it is an interesting comparison.

I hope you enjoy!

My first Pluralsight course titled 'ASP.NET Identity 2 Fundamentals' is due for release Q1 2017.

OAuth Request using .NET

var client = new HttpClient();
var tokenResponse = await client.PostAsync("https://localhost/authorizationserver/connect/token",
    new FormUrlEncodedContent(new List<KeyValuePair<string, string>>
        new KeyValuePair<string, string>("grant_type", "client_credentials"),
        new KeyValuePair<string, string>("scope", "backend_api"),
        new KeyValuePair<string, string>("client_id", "machineClient"),
        new KeyValuePair<string, string>("client_secret", "superSecret"),

var tokenResponseAsString = await tokenResponse.Content.ReadAsStringAsync(); var token = JObject.Parse(tokenResponseAsString)["access_token"].Value<string>();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var result = await client.GetAsync("https://localhost/api/test");

OAuth Request using IdentityModel

var tokenClient = new TokenClient(
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("backend_api");                             

var client = new HttpClient(); client.SetBearerToken(tokenResponse.AccessToken); var result = await client.GetAsync("https://localhost/api/test");