Chapter 4 - jayharris/workshop-oidc GitHub Wiki

Chapter 4: Consuming API Resources

Return to the Console Client created in Chapter 2.

4.1: Add a constant for the API root

ConsoleClient\Program.cs within the Program class:

private const string ApiResource = "http://localhost:5010";

4.2: Change the Client Scope

ConsoleClient\Program.cs within the Program class, change the ClientScope constant:

private const string ClientScope = "apiResource";

4.3: Set the scope for the Client

IdentityProvider\IdentityConfiguration.cs within the GetClients method, for the ConsoleClient client, revised the AllowedScopes setting to apiResource:

new Client
{
  ClientId = "ConsoleClient",
  ClientName = "Identity Server Console Client",
  ClientSecrets =
  {
      new Secret("secretKey".Sha256())
  },
  AllowedGrantTypes = GrantTypes.ClientCredentials,
  AllowedScopes = { "apiResource" }
}

4.4: Send a request to the API Resource

ConsoleClient\Program.cs

using Newtonsoft.Json.Linq;

ConsoleClient\Program.cs append to the MainAsync method of the Program class:

// call api
var apiClient = new HttpClient();
apiClient.SetBearerToken(tokenResponse.AccessToken);

var apiResponse = await apiClient.GetAsync($"{ApiResource}/api/values");
Console.WriteLine($"API Response Code: {(int) apiResponse.StatusCode} {apiResponse.StatusCode}");
if (!apiResponse.IsSuccessStatusCode) return;
var identityResponseContent = await apiResponse.Content.ReadAsStringAsync();
Console.WriteLine($"API Response:\n{JArray.Parse(identityResponseContent)}");

4.5: Run the Provider, API, and test the Console

# From ./src/IdentityProvider/
dotnet run
# From ./src/ApiResource/
dotnet run
# From ./src/ConsoleClient/
dotnet run

# Expected result: A returned API Response Code 200 listing the `["value1","value2"]` JSON responde.