...
- You want to install the IdentityModel package from the NuGet feed into your client project.
This will enable you to shortcut some of the URL mapping and discovery in the OAuth workflow. The following will do this work for you
Code Block language c# theme Confluence firstline 1 title Discovery of IDs Metadata linenumbers true // discover endpoints from metadata var disco = await DiscoveryClient.GetAsync("https://warden.data.uwaterloo.ca"); if (disco.IsError) { Console.WriteLine(disco.Error); return; }
Next you'll pass your credentials to the token server and receive back a JSON response that will include your authorization token.
Code Block language c# theme Confluence firstline 1 title Getting Token from IdentityServer linenumbers true var tokenClient = new TokenClient(disco.TokenEndpoint, "your_client_id", "your_client_password"); var tokenResponse = await tokenClient.RequestClientCredentialsAsync("sourceapi"); if (tokenResponse.IsError) { Console.WriteLine(tokenResponse.Error); return; } Console.WriteLine(tokenResponse.Json);
- Now with your valid token you'll be able to make calls against the API to get data.
To send the access token to the API you typically use the HTTP Authorization header. This is done using the SetBearerToken extension method.
Code Block language c# theme Confluence firstline 1 title Calling the API with Token linenumbers true var client = new HttpClient(); client.SetBearerToken(tokenResponse.AccessToken); var response = await client.GetAsync("https://api.data.uwaterloo.ca/api/v1/terms"); if (!response.IsSuccessStatusCode) { Console.WriteLine(response.StatusCode); } else { var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); }