Accessing OAuth Servers using Flurl

If you have Flurl installed, and you need your client to authenticate against an OAuth2 server, like Identity Server, you can use their client library, which does everything for you (without Flurl), or you can do it yourself.

below is my DIY version.

private const string SECURITY_HOST = "your security host.";
private const string API_HOST = "your test api host";

string.WriteTitle() & string.WriteContent() are extension methods I slapped together to dump the information to the console screen, formatted.

"Ready to start with Flurl...".WriteTitle();
Console.ReadLine();
 
// discover endpoints from metadata
var discoraw = await SECURITY_HOST.AppendPathSegments(".well-known","openid-configuration").GetAsync();
var contentraw = await discoraw.Content.ReadAsStringAsync();
$"Discovery: {discoraw}".WriteContent(title: "Discovery");
$"Disco Content: {contentraw}".WriteContent(title: "Discovery");
var disco = JsonConvert.DeserializeObject(contentraw);
 
// request token
var authorizationAddr = (string)disco.token_endpoint;
 
var authorizationObj = await authorizationAddr.PostUrlEncodedAsync(new { client_id = "client", client_secret = "secret", grant_type = "client_credentials", scope="api1" });
var authorizationString = await authorizationObj.Content.ReadAsStringAsync();
$"Token Response: {authorizationString}".WriteContent(title:"Authorization");
 
var tokenContainer = JsonConvert.DeserializeObject(authorizationString);
  
var apiCall = await $"{API_HOST}/identity".WithOAuthBearerToken((string)tokenContainer.access_token).GetAsync();
 
var apiCallResponse = await apiCall.Content.ReadAsStringAsync();
 
$"Claims from API: {apiCallResponse}".WriteContent(title:"API Call");
 
"Press any key to continue...".WriteTitle();
Console.ReadLine();

Enjoy!

This entry was posted in Brian By Experience. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.