/// <summary>
        /// Sends a discovery document request
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public static async Task <DiscoveryDocumentResponse> GetDiscoveryDocumentAsync(this HttpMessageInvoker client, DiscoveryDocumentRequest request, CancellationToken cancellationToken = default)
        {
            string address;

            if (request.Address.IsPresent())
            {
                address = request.Address;
            }
            else if (client is HttpClient)
            {
                address = ((HttpClient)client).BaseAddress.AbsoluteUri;
            }
            else
            {
                throw new ArgumentException("An address is required.");
            }

            var parsed    = DiscoveryEndpoint.ParseUrl(address);
            var authority = parsed.Authority;
            var url       = parsed.Url;

            if (request.Policy.Authority.IsMissing())
            {
                request.Policy.Authority = authority;
            }

            string jwkUrl = "";

            if (!DiscoveryEndpoint.IsSecureScheme(new Uri(url), request.Policy))
            {
                return(ProtocolResponse.FromException <DiscoveryDocumentResponse>(new InvalidOperationException("HTTPS required"), $"Error connecting to {url}. HTTPS required."));
            }

            try
            {
                var clone = request.Clone();

                clone.Method = HttpMethod.Get;
                clone.Prepare();

                clone.RequestUri = new Uri(url);

                var response = await client.SendAsync(clone, cancellationToken).ConfigureAwait(false);

                string responseContent = null;

                if (response.Content != null)
                {
                    responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }

                if (!response.IsSuccessStatusCode)
                {
                    return(await ProtocolResponse.FromHttpResponseAsync <DiscoveryDocumentResponse>(response, $"Error connecting to {url}: {response.ReasonPhrase}"));
                }

                var disco = await ProtocolResponse.FromHttpResponseAsync <DiscoveryDocumentResponse>(response, request.Policy).ConfigureAwait(false);

                if (disco.IsError)
                {
                    return(disco);
                }

                try
                {
                    jwkUrl = disco.JwksUri;
                    if (jwkUrl != null)
                    {
                        var jwkClone = request.Clone <JsonWebKeySetRequest>();
                        jwkClone.Method  = HttpMethod.Get;
                        jwkClone.Address = jwkUrl;
                        jwkClone.Prepare();

                        var jwkResponse = await client.GetJsonWebKeySetAsync(jwkClone, cancellationToken).ConfigureAwait(false);

                        if (jwkResponse.IsError)
                        {
                            return(await ProtocolResponse.FromHttpResponseAsync <DiscoveryDocumentResponse>(jwkResponse.HttpResponse, $"Error connecting to {jwkUrl}: {jwkResponse.HttpErrorReason}").ConfigureAwait(false));
                        }

                        disco.KeySet = jwkResponse.KeySet;
                    }

                    return(disco);
                }
                catch (Exception ex)
                {
                    return(ProtocolResponse.FromException <DiscoveryDocumentResponse>(ex, $"Error connecting to {jwkUrl}. {ex.Message}."));
                }
            }
            catch (Exception ex)
            {
                return(ProtocolResponse.FromException <DiscoveryDocumentResponse>(ex, $"Error connecting to {url}. {ex.Message}."));
            }
        }
        /// <summary>
        /// Retrieves the discovery document.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public virtual async Task <DiscoveryResponse> GetAsync(CancellationToken cancellationToken = default)
        {
            if (Policy.Authority.IsMissing())
            {
                Policy.Authority = Authority;
            }

            string jwkUrl = "";

            if (!DiscoveryEndpoint.IsSecureScheme(new Uri(Url), Policy))
            {
                return(new DiscoveryResponse(new InvalidOperationException("HTTPS required"), $"Error connecting to {Url}"));
            }

            try
            {
                var response = await Client.GetAsync(Url, cancellationToken).ConfigureAwait(false);

                string responseContent = null;

                if (response.Content != null)
                {
                    responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }

                if (!response.IsSuccessStatusCode)
                {
                    return(new DiscoveryResponse(response.StatusCode, $"Error connecting to {Url}: {response.ReasonPhrase}", responseContent));
                }

                var disco = new DiscoveryResponse(responseContent, Policy);
                if (disco.IsError)
                {
                    return(disco);
                }

                try
                {
                    jwkUrl = disco.JwksUri;
                    if (jwkUrl != null)
                    {
                        response = await Client.GetAsync(jwkUrl, cancellationToken).ConfigureAwait(false);

                        if (response.Content != null)
                        {
                            responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        }

                        if (!response.IsSuccessStatusCode)
                        {
                            return(new DiscoveryResponse(response.StatusCode, $"Error connecting to {jwkUrl}: {response.ReasonPhrase}", responseContent));
                        }

                        disco.KeySet = new JsonWebKeySet(responseContent);
                    }

                    return(disco);
                }
                catch (Exception ex)
                {
                    return(new DiscoveryResponse(ex, $"Error connecting to {jwkUrl}"));
                }
            }
            catch (Exception ex)
            {
                return(new DiscoveryResponse(ex, $"Error connecting to {Url}"));
            }
        }
Exemple #3
0
        /// <summary>
        /// Validates the endoints and jwks_uri according to the security policy.
        /// </summary>
        /// <param name="json">The json.</param>
        /// <param name="policy">The policy.</param>
        /// <returns></returns>
        public string ValidateEndpoints(JsonElement json, DiscoveryPolicy policy)
        {
            // allowed hosts
            var allowedHosts = new HashSet <string>(policy.AdditionalEndpointBaseAddresses.Select(e => new Uri(e).Authority))
            {
                new Uri(policy.Authority).Authority
            };

            // allowed authorities (hosts + base address)
            var allowedAuthorities = new HashSet <string>(policy.AdditionalEndpointBaseAddresses)
            {
                policy.Authority
            };

            foreach (var element in json.EnumerateObject())
            {
                if (element.Name.EndsWith("endpoint", StringComparison.OrdinalIgnoreCase) ||
                    element.Name.Equals(OidcConstants.Discovery.JwksUri, StringComparison.OrdinalIgnoreCase) ||
                    element.Name.Equals(OidcConstants.Discovery.CheckSessionIframe, StringComparison.OrdinalIgnoreCase))
                {
                    var endpoint = element.Value.ToString();

                    var isValidUri = Uri.TryCreate(endpoint, UriKind.Absolute, out Uri uri);
                    if (!isValidUri)
                    {
                        return($"Malformed endpoint: {endpoint}");
                    }

                    if (!DiscoveryEndpoint.IsValidScheme(uri))
                    {
                        return($"Malformed endpoint: {endpoint}");
                    }

                    if (!DiscoveryEndpoint.IsSecureScheme(uri, policy))
                    {
                        return($"Endpoint does not use HTTPS: {endpoint}");
                    }

                    if (policy.ValidateEndpoints)
                    {
                        // if endpoint is on exclude list, don't validate
                        if (policy.EndpointValidationExcludeList.Contains(element.Name))
                        {
                            continue;
                        }

                        bool isAllowed = false;
                        foreach (var host in allowedHosts)
                        {
                            if (string.Equals(host, uri.Authority))
                            {
                                isAllowed = true;
                            }
                        }

                        if (!isAllowed)
                        {
                            return($"Endpoint is on a different host than authority: {endpoint}");
                        }

                        IAuthorityValidationStrategy strategy = policy.AuthorityValidationStrategy ?? DiscoveryPolicy.DefaultAuthorityValidationStrategy;
                        AuthorityValidationResult    endpointValidationResult = strategy.IsEndpointValid(endpoint, allowedAuthorities);
                        if (!endpointValidationResult.Success)
                        {
                            return(endpointValidationResult.ErrorMessage);
                        }
                    }
                }
            }

            if (policy.RequireKeySet)
            {
                if (string.IsNullOrWhiteSpace(JwksUri))
                {
                    return("Keyset is missing");
                }
            }

            return(string.Empty);
        }
        /// <summary>
        /// Sends a discovery document request
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public static async Task <DiscoveryResponse> GetDiscoveryDocumentAsync(this HttpClient client, DiscoveryDocumentRequest request = null, CancellationToken cancellationToken = default)
        {
            if (request == null)
            {
                request = new DiscoveryDocumentRequest();
            }

            string address;

            if (request.Address.IsPresent())
            {
                address = request.Address;
            }
            else
            {
                address = client.BaseAddress.AbsoluteUri;
            }

            var parsed    = DiscoveryClient.ParseUrl(address);
            var authority = parsed.Authority;
            var url       = parsed.Url;

            if (request.Policy.Authority.IsMissing())
            {
                request.Policy.Authority = authority;
            }

            string jwkUrl = "";

            if (!DiscoveryEndpoint.IsSecureScheme(new Uri(url), request.Policy))
            {
                return(new DiscoveryResponse(new InvalidOperationException("HTTPS required"), $"Error connecting to {url}"));
            }

            try
            {
                var httpRequest = new HttpRequestMessage(HttpMethod.Get, url);
                var response    = await client.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                string responseContent = null;

                if (response.Content != null)
                {
                    responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }

                if (!response.IsSuccessStatusCode)
                {
                    return(new DiscoveryResponse(response.StatusCode, $"Error connecting to {url}: {response.ReasonPhrase}", responseContent));
                }

                var disco = new DiscoveryResponse(responseContent, request.Policy);
                if (disco.IsError)
                {
                    return(disco);
                }

                try
                {
                    jwkUrl = disco.JwksUri;
                    if (jwkUrl != null)
                    {
                        response = await client.GetAsync(jwkUrl, cancellationToken).ConfigureAwait(false);

                        if (response.Content != null)
                        {
                            responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        }

                        if (!response.IsSuccessStatusCode)
                        {
                            return(new DiscoveryResponse(response.StatusCode, $"Error connecting to {jwkUrl}: {response.ReasonPhrase}", responseContent));
                        }

                        disco.KeySet = new JsonWebKeySet(responseContent);
                    }

                    return(disco);
                }
                catch (Exception ex)
                {
                    return(new DiscoveryResponse(ex, $"Error connecting to {jwkUrl}"));
                }
            }
            catch (Exception ex)
            {
                return(new DiscoveryResponse(ex, $"Error connecting to {url}"));
            }
        }