6

Consuming External OAuth Services using IdentityModel

 2 years ago
source link: https://www.scottbrady91.com/oauth/consuming-external-oauth-services-using-identitymodel
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Consuming External OAuth Services using IdentityModel

IdentityModel

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(
    "https://localhost/authorizationserver/connect/token",
    "machineClient",
    "superSecret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("backend_api");                             

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK