My work duties have recently grown to include the architecture, installation, configuration, and care and feeding or our brand new single sign on (SSO) server, Ping Identity’s Ping Federate.

I’ve recently read a lot of documentation and with the benefit of a Ping Identity architect have come up with a bunch of samples to be used by our internal developers.

The first snippet that I have is the most simple: using the HttpClient to fetch a token through the OAuth 2 Client Credential Flow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using(HttpClient client = new HttpClient())
{
var bytes = System.Text.Encoding.UTF8.GetBytes("your client ID" + ":" + "your client secret");
var basicAuthenticationHeader = System.Convert.ToBase64String(bytes);

var content = new StringContent("grant_type=client_credentials&scope=edit");
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://localhost:9031/as/token.oauth2"),
Method = HttpMethod.Post,
Content = content,
};

request.Headers.Authorization = new AuthenticationHeaderValue("Basic", basicAuthenticationHeader);

var results = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result;

dynamic token = JsonConvert.DeserializeObject<dynamic>(results);
}

Once you have the token, you can use the token.access_token as a bearer token in an Authorization header to call other OAuth2 secured web services.