Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OpenID Connect - Validate Discovery Endpoint response #1981

Merged
merged 17 commits into from
Aug 15, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions src/HealthChecks.OpenIdConnectServer/DiscoveryEndpointResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using System.Text.Json.Serialization;

namespace HealthChecks.IdSvr;

internal class DiscoveryEndpointResponse
{
[JsonPropertyName(OidcConstants.ISSUER)]
public string Issuer { get; set; } = null!;

[JsonPropertyName(OidcConstants.AUTHORIZATION_ENDPOINT)]
public string AuthorizationEndpoint { get; set; } = null!;

[JsonPropertyName(OidcConstants.JWKS_URI)]
public string JwksUri { get; set; } = null!;

[JsonPropertyName(OidcConstants.RESPONSE_TYPES_SUPPORTED)]
public string[] ResponseTypesSupported { get; set; } = null!;

[JsonPropertyName(OidcConstants.SUBJECT_TYPES_SUPPORTED)]
public string[] SubjectTypesSupported { get; set; } = null!;

[JsonPropertyName(OidcConstants.ALGORITHMS_SUPPORTED)]
public string[] IdTokenSigningAlgValuesSupported { get; set; } = null!;

/// <summary>
/// Validates Discovery response according to the <see href="https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata">OpenID specification</see>
/// </summary>
public void ValidateResponse()
{
ValidateValue(Issuer, OidcConstants.ISSUER);
ValidateValue(AuthorizationEndpoint, OidcConstants.AUTHORIZATION_ENDPOINT);
ValidateValue(JwksUri, OidcConstants.JWKS_URI);

ValidateRequiredValues(ResponseTypesSupported, OidcConstants.RESPONSE_TYPES_SUPPORTED, OidcConstants.REQUIRED_RESPONSE_TYPES);
ValidateRequiredValues(SubjectTypesSupported, OidcConstants.SUBJECT_TYPES_SUPPORTED, OidcConstants.REQUIRED_SUBJECT_TYPES);
ValidateRequiredValues(IdTokenSigningAlgValuesSupported, OidcConstants.ALGORITHMS_SUPPORTED, OidcConstants.REQUIRED_ALGORITHMS);
}

private static void ValidateValue(string value, string metadata)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException(GetMissingValueExceptionMessage(metadata));
}
}

private static void ValidateRequiredValues(IEnumerable<string> values, string metadata, string[] requiredValues)
sungam3r marked this conversation as resolved.
Show resolved Hide resolved
{
if (values == null || !AnyValueContains(values, requiredValues))

Check failure on line 49 in src/HealthChecks.OpenIdConnectServer/DiscoveryEndpointResponse.cs

View workflow job for this annotation

GitHub Actions / build

Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable<string>' to 'string[]'

Check failure on line 49 in src/HealthChecks.OpenIdConnectServer/DiscoveryEndpointResponse.cs

View workflow job for this annotation

GitHub Actions / build

Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable<string>' to 'string[]'
{
throw new ArgumentException(GetMissingRequiredValuesExceptionMessage(metadata, requiredValues));
}
}

private static bool AnyValueContains(string[] values, string[] requiredValues) =>
values.Any(v => requiredValues.Contains(v));

private static string GetMissingValueExceptionMessage(string value) =>
$"Invalid discovery response - '{value}' must be set!";

private static string GetMissingRequiredValuesExceptionMessage(string value, string[] requiredValues) =>
$"Invalid discovery response - '{value}' must be one of the following values: {string.Join(",", requiredValues)}!";
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="7.0.9" />
<PackageReference Include=" System.Net.Http.Json" Version="7.0.1" />
</ItemGroup>

</Project>
18 changes: 15 additions & 3 deletions src/HealthChecks.OpenIdConnectServer/IdSvrHealthCheck.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;

Expand Down Expand Up @@ -27,9 +28,20 @@ public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context
var httpClient = _httpClientFactory();
using var response = await httpClient.GetAsync(_discoverConfigurationSegment, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

return response.IsSuccessStatusCode
? HealthCheckResult.Healthy()
: new HealthCheckResult(context.Registration.FailureStatus, description: $"Discover endpoint is not responding with 200 OK, the current status is {response.StatusCode} and the content {await response.Content.ReadAsStringAsync().ConfigureAwait(false)}");
if (!response.IsSuccessStatusCode)
{
return new HealthCheckResult(context.Registration.FailureStatus, description: $"Discover endpoint is not responding with 200 OK, the current status is {response.StatusCode} and the content {await response.Content.ReadAsStringAsync().ConfigureAwait(false)}");
}

var discoveryResponse = await response
.Content
.ReadFromJsonAsync<DiscoveryEndpointResponse>()
.ConfigureAwait(false)
?? throw new ArgumentException("Could not deserialize to discovery endpoint response!");

discoveryResponse.ValidateResponse();

return HealthCheckResult.Healthy();
}
catch (Exception ex)
{
Expand Down
22 changes: 22 additions & 0 deletions src/HealthChecks.OpenIdConnectServer/OidcConstants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace HealthChecks.IdSvr;

internal class OidcConstants
{
internal const string ISSUER = "issuer";

internal const string AUTHORIZATION_ENDPOINT = "authorization_endpoint";

internal const string JWKS_URI = "jwks_uri";

internal const string RESPONSE_TYPES_SUPPORTED = "response_types_supported";

internal const string SUBJECT_TYPES_SUPPORTED = "subject_types_supported";

internal const string ALGORITHMS_SUPPORTED = "id_token_signing_alg_values_supported";

internal static string[] REQUIRED_RESPONSE_TYPES => new[] { "code", "id_token", "token id_token" };

internal static string[] REQUIRED_SUBJECT_TYPES => new[] { "pairwise", "public" };

internal static string[] REQUIRED_ALGORITHMS => new[] { "RS256" };
}
Loading