Example #1
0
        public async Task GetOpenIdConfiguration()
        {
            // Arrange
            HttpClient client = GetTestClient();

            HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "/authentication/api/v1/OpenId/.well-known/openid-configuration");

            // Act
            HttpResponseMessage response = await client.SendAsync(requestMessage);

            // Assert
            string json = await response.Content.ReadAsStringAsync();

            DiscoveryDocument discoveryDocument = JsonSerializer.Deserialize <DiscoveryDocument>(json);

            Assert.NotNull(discoveryDocument);
            Assert.EndsWith("jwks", discoveryDocument.JwksUri);
        }
Example #2
0
    static void Main()
    {
        try
        {
            // Create an object of the 'DiscoveryDocument'.
            DiscoveryDocument myDiscoveryDocument = new DiscoveryDocument();

            // Create an XmlTextReader with the sample file.
            XmlTextReader myXmlTextReader = new
                                            XmlTextReader("http://localhost/example_cs.disco");

            // Read the given XmlTextReader.
            myDiscoveryDocument = DiscoveryDocument.Read(myXmlTextReader);

// <Snippet2>
            // Write the DiscoveryDocument into the 'TextWriter'.
            FileStream myFileStream = new
                                      FileStream("log.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter myStreamWriter = new StreamWriter(myFileStream);
            myDiscoveryDocument.Write(myStreamWriter);

            myStreamWriter.Flush();
            myStreamWriter.Close();
// </Snippet2>

            // Display the contents of the DiscoveryDocument onto the console.
            FileStream myFileStream1 = new
                                       FileStream("log.txt", FileMode.OpenOrCreate, FileAccess.Read);
            StreamReader myStreamReader = new StreamReader(myFileStream1);

            // Set the file pointer to the begin.
            myStreamReader.BaseStream.Seek(0, SeekOrigin.Begin);
            Console.WriteLine("The contents of the DiscoveryDocument are-");
            while (myStreamReader.Peek() > -1)
            {
                Console.WriteLine(myStreamReader.ReadLine());
            }
            myStreamReader.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception raised : {0}", e.Message);
        }
    }
        internal DiscoveryServerType(Type type, string uri) : base(typeof(DiscoveryServerProtocol))
        {
            this.schemaTable = new Hashtable();
            this.wsdlTable   = new Hashtable();
            uri             = new Uri(uri, true).GetLeftPart(UriPartial.Path);
            this.methodInfo = new LogicalMethodInfo(typeof(DiscoveryServerProtocol).GetMethod("Discover", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance));
            ServiceDescriptionReflector reflector = new ServiceDescriptionReflector();

            reflector.Reflect(type, uri);
            XmlSchemas schemas = reflector.Schemas;

            this.description = reflector.ServiceDescription;
            XmlSerializer serializer = ServiceDescription.Serializer;

            this.AddSchemaImports(schemas, uri, reflector.ServiceDescriptions);
            for (int i = 1; i < reflector.ServiceDescriptions.Count; i++)
            {
                ServiceDescription description = reflector.ServiceDescriptions[i];
                Import             import      = new Import {
                    Namespace = description.TargetNamespace
                };
                string key = "wsdl" + i.ToString(CultureInfo.InvariantCulture);
                import.Location = uri + "?wsdl=" + key;
                reflector.ServiceDescription.Imports.Add(import);
                this.wsdlTable.Add(key, description);
            }
            this.discoDoc = new DiscoveryDocument();
            this.discoDoc.References.Add(new ContractReference(uri + "?wsdl", uri));
            foreach (Service service in reflector.ServiceDescription.Services)
            {
                foreach (Port port in service.Ports)
                {
                    SoapAddressBinding binding = (SoapAddressBinding)port.Extensions.Find(typeof(SoapAddressBinding));
                    if (binding != null)
                    {
                        System.Web.Services.Discovery.SoapBinding binding2 = new System.Web.Services.Discovery.SoapBinding {
                            Binding = port.Binding,
                            Address = binding.Location
                        };
                        this.discoDoc.References.Add(binding2);
                    }
                }
            }
        }
Example #4
0
        /// <summary>
        /// Called after an asynchronous web services search has
        /// completed.
        /// </summary>
        private void DiscoveryCompleted(IAsyncResult result)
        {
            AsyncDiscoveryState state = (AsyncDiscoveryState)result.AsyncState;
            WebServiceDiscoveryClientProtocol protocol = state.Protocol;

            // Check that we are still waiting for this particular callback.
            bool wanted = false;

            lock (this)
            {
                wanted = Object.ReferenceEquals(_discoveryClientProtocol, protocol);
            }

            if (wanted)
            {
                DiscoveredWebServicesHandler handler = new DiscoveredWebServicesHandler(DiscoveredWebServices);
                try
                {
                    DiscoverAnyAsync  asyncDelegate = (DiscoverAnyAsync)((AsyncResult)result).AsyncDelegate;
                    DiscoveryDocument doc           = asyncDelegate.EndInvoke(result);
                    if (!state.Credential.IsDefaultAuthenticationType)
                    {
                        AddCredential(state.Uri, state.Credential);
                    }
                    Invoke(handler, new object[] { protocol });
                }
                catch
                {
                    if (protocol.IsAuthenticationRequired)
                    {
                        HttpAuthenticationHeader authHeader  = protocol.GetAuthenticationHeader();
                        AuthenticationHandler    authHandler = new AuthenticationHandler(AuthenticateUser);
                        Invoke(authHandler, new object[] { state.Uri, authHeader.AuthenticationType });
                    }
                    else
                    {
                        //LoggingService.Error("DiscoveryCompleted", ex);
                        Invoke(handler, new object[] { null });
                    }
                }
            }
        }
    static void Run()
    {
        try
        {
            // 'dataservice.disco' is a sample discovery document.
            string myStringUrl = "http://localhost/dataservice.disco";

            // Call the Discover method to populate the Documents property.
            DiscoveryClientProtocol myDiscoveryClientProtocol =
                new DiscoveryClientProtocol();
            myDiscoveryClientProtocol.Credentials =
                CredentialCache.DefaultCredentials;
            DiscoveryDocument myDiscoveryDocument =
                myDiscoveryClientProtocol.Discover(myStringUrl);

            Console.WriteLine("Demonstrating the Discovery.SoapBinding class.");

            // Create a SOAP binding.
            SoapBinding mySoapBinding = new SoapBinding();

            // Assign an address to the created SOAP binding.
            mySoapBinding.Address = "http://schemas.xmlsoap.org/disco/scl/";

            // Bind the created SOAP binding with a new XmlQualifiedName.
            mySoapBinding.Binding = new XmlQualifiedName("string",
                                                         "http://www.w3.org/2001/XMLSchema");

            // Add the created SOAP binding to the DiscoveryClientProtocol.
            myDiscoveryClientProtocol.AdditionalInformation.Add(mySoapBinding);

            // Display the namespace associated with SOAP binding.
            Console.WriteLine("Namespace associated with the SOAP binding is: "
                              + SoapBinding.Namespace);

            // Write all the information of the DiscoveryClientProtocol.
            myDiscoveryClientProtocol.WriteAll(".", "results.discomap");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
Example #6
0
    public static void Main()
    {
        try
        {
            DiscoveryDocument myDiscoveryDocument;
            XmlTextReader     myXmlTextReader =
                new XmlTextReader("http://localhost/Sample_cs.vsdisco");
            myDiscoveryDocument = DiscoveryDocument.Read(myXmlTextReader);

            // <Snippet2>
            // Create a new instance of DiscoveryDocumentReference.
            DiscoveryDocumentReference myDiscoveryDocumentReference =
                new DiscoveryDocumentReference();
            // </Snippet2>
            // <Snippet3>
            FileStream myFileStream = new FileStream("Temp.vsdisco",
                                                     FileMode.OpenOrCreate, FileAccess.Write);
            myDiscoveryDocumentReference.WriteDocument(
                myDiscoveryDocument, myFileStream);
            myFileStream.Close();
            // </Snippet3>

            FileStream myFileStream1 = new FileStream("Temp.vsdisco",
                                                      FileMode.OpenOrCreate, FileAccess.Read);
            StreamReader myStreamReader = new StreamReader(myFileStream1);

            // Initialize the file pointer.
            myStreamReader.BaseStream.Seek(0, SeekOrigin.Begin);
            Console.WriteLine("The contents of the discovery document are: \n");
            while (myStreamReader.Peek() > -1)
            {
                // Display the contents of the discovery document.
                Console.WriteLine(myStreamReader.ReadLine());
            }
            myStreamReader.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: {0}", e.Message);
        }
    }
    static void Main()
    {
        try
        {
            // Get a DiscoveryDocument.
            DiscoveryDocument myDiscoveryDocument = new  DiscoveryDocument();

            // Get a ContractReference.
            ContractReference myContractReference = new ContractReference();

            // Set the URL to the referenced service description.
            myContractReference.Ref = "http://localhost/service1.asmx?wsdl";

            // Set the URL for an XML Web service implementing the service
            // description.
            myContractReference.DocRef = "http://localhost/service1.asmx";
            SoapBinding myBinding = new SoapBinding();
            myBinding.Binding = new XmlQualifiedName("q1:Service1Soap");
            myBinding.Address = "http://localhost/service1.asmx";

            // Add myContractReference to the list of references contained
            // in the discovery document.
            myDiscoveryDocument.References.Add(myContractReference);

            // Add Binding to the references collection.
            myDiscoveryDocument.References.Add(myBinding);

            // Open or create a file for writing.
            FileStream myFileStream = new FileStream("Service1.disco",
                                                     FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter myStreamWriter = new StreamWriter(myFileStream);

            // Write myDiscoveryDocument into the passed stream.
            myDiscoveryDocument.Write(myStreamWriter);
            Console.WriteLine("The Service1.disco is generated.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Error is " + e.Message);
        }
    }
Example #8
0
 private void ProcessRemoteUrls(DiscoveryClientProtocol client, StringCollection urls, XmlSchemas schemas,
                                ServiceDescriptionCollection descriptions)
 {
     foreach (string text1 in urls)
     {
         try
         {
             DiscoveryDocument document1 = client.DiscoverAny(text1);
             client.ResolveAll();
             continue;
         }
         catch (Exception exception1)
         {
             throw new InvalidOperationException("General Error " + text1, exception1);
         }
     }
     foreach (DictionaryEntry entry1 in client.Documents)
     {
         AddDocument((string)entry1.Key, entry1.Value, schemas, descriptions);
     }
 }
Example #9
0
 /// <summary>Generate a text description for the a DiscoverDocument.</summary>
 /// <param name="doc">A DiscoveryDocument containing the details for the disco services.</param>
 /// <returns>An XmlDocument containing the generated xml for the specified discovery document.</returns>
 public static void GenerateDiscoXml(StringBuilder text, DiscoveryDocument doc)
 {
     text.Append("<big><b>" + GettextCatalog.GetString("Web Service References") + "</b></big>\n\n");
     foreach (object oref in doc.References)
     {
         var dref = oref as DiscoveryReference;
         if (dref == null)
         {
             continue;
         }
         if (dref is ContractReference)
         {
             text.AppendFormat("<b>" + GettextCatalog.GetString("Service: {0}") + "</b>\n<span size='small'>{1}</span>", Path.GetFileNameWithoutExtension(dref.DefaultFilename), dref.Url);
         }
         else if (dref is DiscoveryDocumentReference)
         {
             text.AppendFormat("<b>" + GettextCatalog.GetString("Discovery document") + "</b>\n<small>{0}</small>", dref.Url);
         }
         text.Append("\n\n");
     }
 }
    static void Run()
    {
        try
        {
// <Snippet1>
            string myUrl = "http://localhost/Sample_cs.vsdisco";
            DiscoveryClientProtocol myProtocol = new DiscoveryClientProtocol();
            // Get the discovery document myDiscoveryDocument.
            DiscoveryDocument myDiscoveryDocument = myProtocol.Discover(myUrl);
            // Get the references of myDiscoveryDocument.
            IEnumerator myEnumerator = myDiscoveryDocument.References.GetEnumerator();
            while (myEnumerator.MoveNext())
            {
                DiscoveryDocumentReference myNewReference =
                    (DiscoveryDocumentReference)myEnumerator.Current;
                // Set the ClientProtocol of myNewReference.
                DiscoveryClientProtocol myNewProtocol = myNewReference.ClientProtocol;
                // Verify for all the valid references.
                myNewReference.ResolveAll();

                // Get the document of myNewReference.
                DiscoveryDocument myNewDiscoveryDocument =
                    myNewReference.Document;

                IEnumerator myNewEnumerator =
                    myNewDiscoveryDocument.References.GetEnumerator();
                Console.WriteLine("The valid discovery document is : \n");
                while (myNewEnumerator.MoveNext())
                {
                    // Display the references of myNewDiscoveryDocument on the console.
                    Console.WriteLine(((DiscoveryDocumentReference)myNewEnumerator.Current).Ref);
                }
            }
// </Snippet1>
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception :{0}", e.Message);
        }
    }
    public static void Main()
    {
// <Snippet1>
        string myDiscoFile = "http://localhost/MathService_cs.vsdisco";
        string myUrlKey    = "http://localhost/MathService_cs.asmx?wsdl";
        DiscoveryClientProtocol myDiscoveryClientProtocol =
            new DiscoveryClientProtocol();

        // Get the discovery document.
        DiscoveryDocument myDiscoveryDocument =
            myDiscoveryClientProtocol.Discover(myDiscoFile);
        IEnumerator myEnumerator =
            myDiscoveryDocument.References.GetEnumerator();

        while (myEnumerator.MoveNext())
        {
            ContractReference myContractReference =
                (ContractReference)myEnumerator.Current;

            // Get the DiscoveryClientProtocol from the ContractReference.
            myDiscoveryClientProtocol = myContractReference.ClientProtocol;
            myDiscoveryClientProtocol.ResolveAll();

            DiscoveryExceptionDictionary myExceptionDictionary
                = myDiscoveryClientProtocol.Errors;

            if (myExceptionDictionary.Contains(myUrlKey))
            {
                Console.WriteLine("System generated exceptions.");

                // Get the exception from the DiscoveryExceptionDictionary.
                Exception myException = myExceptionDictionary[myUrlKey];

                Console.WriteLine(" Source : " + myException.Source);
                Console.WriteLine(" Exception : " + myException.Message);
            }
        }
// </Snippet1>
    }
Example #12
0
    static void Run()
    {
        try
        {
            // dataservice.disco is a sample discovery document.
            string myStringUrl = "http://localhost/dataservice.disco";

            // Call the Discover method to populate the Documents property.
            DiscoveryClientProtocol myDiscoveryClientProtocol =
                new DiscoveryClientProtocol();
            myDiscoveryClientProtocol.Credentials =
                CredentialCache.DefaultCredentials;
            DiscoveryDocument myDiscoveryDocument =
                myDiscoveryClientProtocol.Discover(myStringUrl);

            SoapBinding mySoapBinding = new SoapBinding();
            mySoapBinding.Address = "http://schemas.xmlsoap.org/disco/scl/";
            mySoapBinding.Binding = new XmlQualifiedName("string",
                                                         "http://www.w3.org/2001/XMLSchema");
            myDiscoveryClientProtocol.AdditionalInformation.Add(mySoapBinding);

            // Write the information back.
            myDiscoveryClientProtocol.WriteAll("MyDirectory",
                                               "results.discomap");

            System.Collections.IList myIList =
                myDiscoveryClientProtocol.AdditionalInformation;
            mySoapBinding = null;
            mySoapBinding = (SoapBinding)myIList[0];
            Console.WriteLine("The address of the SoapBinding associated "
                              + "with AdditionalInformation is: "
                              + mySoapBinding.Address);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
Example #13
0
        /// <include file='doc\SoapClientProtocol.uex' path='docs/doc[@for="SoapHttpClientProtocol.Discover"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void Discover()
        {
            if (clientType.Binding == null)
            {
                throw new InvalidOperationException(Res.GetString(Res.DiscoveryIsNotPossibleBecauseTypeIsMissing1, this.GetType().FullName));
            }
            DiscoveryClientProtocol disco = new DiscoveryClientProtocol(this);
            DiscoveryDocument       doc   = disco.Discover(Url);

            foreach (object item in doc.References)
            {
                System.Web.Services.Discovery.SoapBinding soapBinding = item as System.Web.Services.Discovery.SoapBinding;
                if (soapBinding != null)
                {
                    if (clientType.Binding.Name == soapBinding.Binding.Name &&
                        clientType.Binding.Namespace == soapBinding.Binding.Namespace)
                    {
                        Url = soapBinding.Address;
                        return;
                    }
                }
            }
            throw new InvalidOperationException(Res.GetString(Res.TheBindingNamedFromNamespaceWasNotFoundIn3, clientType.Binding.Name, clientType.Binding.Namespace, Url));
        }
    static void Main()
    {
        string myDiscoFile = "http://localhost/MathService_cs.disco";
        string myUrlKey    = "http://localhost/MathService_cs.asmx?wsdl";
        DiscoveryClientProtocol myDiscoveryClientProtocol1 =
            new DiscoveryClientProtocol();
        DiscoveryDocument myDiscoveryDocument =
            myDiscoveryClientProtocol1.Discover(myDiscoFile);
        IEnumerator myEnumerator =
            myDiscoveryDocument.References.GetEnumerator();

        while (myEnumerator.MoveNext())
        {
            ContractReference myContractReference =
                (ContractReference)myEnumerator.Current;
            DiscoveryClientProtocol myDiscoveryClientProtocol2 =
                myContractReference.ClientProtocol;
            myDiscoveryClientProtocol2.ResolveAll();
            DiscoveryExceptionDictionary myExceptionDictionary
                = myDiscoveryClientProtocol2.Errors;
            if (myExceptionDictionary.Contains(myUrlKey) == true)
            {
                Console.WriteLine("'myExceptionDictionary' contains " +
                                  " a discovery exception for the key '" + myUrlKey + "'");
            }
            else
            {
                Console.WriteLine("'myExceptionDictionary' does not contain" +
                                  " a discovery exception for the key '" + myUrlKey + "'");
            }
            if (myExceptionDictionary.Contains(myUrlKey) == true)
            {
                Console.WriteLine("System generated exceptions.");

                Exception myException = myExceptionDictionary[myUrlKey];
                Console.WriteLine(" Source : " + myException.Source);
                Console.WriteLine(" Exception : " + myException.Message);

                Console.WriteLine();

                // Remove the discovery exception.for the key 'myUrlKey'.
                myExceptionDictionary.Remove(myUrlKey);

                DiscoveryExceptionDictionary myNewExceptionDictionary =
                    new DiscoveryExceptionDictionary();
                // Add an exception with the custom error message.
                Exception myNewException =
                    new Exception("The requested service is not available.");
                myNewExceptionDictionary.Add(myUrlKey, myNewException);
                myExceptionDictionary = myNewExceptionDictionary;

                Console.WriteLine("Added exceptions.");

                object[] myArray = new object[myExceptionDictionary.Count];
                myExceptionDictionary.Keys.CopyTo((Array)myArray, 0);
                Console.WriteLine(" Keys are :");
                foreach (object myObj in myArray)
                {
                    Console.WriteLine(" " + myObj.ToString());
                }

                Console.WriteLine();

                object[] myCollectionArray = new object[myExceptionDictionary.Count];
                myExceptionDictionary.Values.CopyTo((Array)myCollectionArray, 0);
                Console.WriteLine(" Values are :");
                foreach (object myObj in myCollectionArray)
                {
                    Console.WriteLine(" " + myObj.ToString());
                }
            }
        }
    }
        // See comment on the ServerProtocol.IsCacheUnderPressure method for explanation of the excludeSchemeHostPortFromCachingKey logic.
        internal DiscoveryServerType(Type type, string uri, bool excludeSchemeHostPortFromCachingKey)
            : base(typeof(DiscoveryServerProtocol))
        {
            if (excludeSchemeHostPortFromCachingKey)
            {
                this.UriFixups = new List <Action <Uri> >();
            }
            //
            // parse the uri from a string into a Uri object
            //
            Uri uriObject = new Uri(uri, true);

            //
            // and get rid of the query string if there's one
            //
            uri        = uriObject.GetLeftPart(UriPartial.Path);
            methodInfo = new LogicalMethodInfo(typeof(DiscoveryServerProtocol).GetMethod("Discover", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
            ServiceDescriptionReflector reflector = new ServiceDescriptionReflector(this.UriFixups);

            reflector.Reflect(type, uri);

            XmlSchemas schemas = reflector.Schemas;

            this.description = reflector.ServiceDescription;

            // We need to force initialization of ServiceDescription's XmlSerializer since we
            // won't necessarily have the permissions to do it when we actually need it
            XmlSerializer serializer = ServiceDescription.Serializer;

            // add imports to the external schemas
            AddSchemaImports(schemas, uri, reflector.ServiceDescriptions);

            // add imports to the other service descriptions
            for (int i = 1; i < reflector.ServiceDescriptions.Count; i++)
            {
                ServiceDescription description = reflector.ServiceDescriptions[i];
                Import             import      = new Import();
                import.Namespace = description.TargetNamespace;

                //


                string id = "wsdl" + i.ToString(CultureInfo.InvariantCulture);

                import.Location = uri + "?wsdl=" + id;
                this.AddUriFixup(delegate(Uri current)
                {
                    import.Location = CombineUris(current, import.Location);
                });
                reflector.ServiceDescription.Imports.Add(import);
                wsdlTable.Add(id, description);
            }

            discoDoc = new DiscoveryDocument();
            ContractReference contractReference = new ContractReference(uri + "?wsdl", uri);

            this.AddUriFixup(delegate(Uri current)
            {
                contractReference.Ref    = CombineUris(current, contractReference.Ref);
                contractReference.DocRef = CombineUris(current, contractReference.DocRef);
            });
            discoDoc.References.Add(contractReference);

            foreach (Service service in reflector.ServiceDescription.Services)
            {
                foreach (Port port in service.Ports)
                {
                    SoapAddressBinding soapAddress = (SoapAddressBinding)port.Extensions.Find(typeof(SoapAddressBinding));
                    if (soapAddress != null)
                    {
                        System.Web.Services.Discovery.SoapBinding binding = new System.Web.Services.Discovery.SoapBinding();
                        binding.Binding = port.Binding;
                        binding.Address = soapAddress.Location;
                        this.AddUriFixup(delegate(Uri current)
                        {
                            binding.Address = CombineUris(current, binding.Address);
                        });
                        discoDoc.References.Add(binding);
                    }
                }
            }
        }
Example #16
0
 public static IdentityProviderModel ToClientModel(this IdentityProviderEntity entity, DiscoveryDocument discoveryDocument)
 {
     return(new IdentityProviderModel
     {
         ClientId = entity.ClientId,
         DisplayName = entity.DisplayName,
         IconUrl = entity.IconUrl,
         AuthorizeUrl = discoveryDocument.AuthorizationEndpoint
     });
 }
Example #17
0
        private void DownloadWSDL()
        {
            DiscoveryClientDocument = DiscoveryClient.DiscoverAny(_endpointUri.ToString());

            DiscoveryClient.ResolveAll();
            DiscoveryContractReference = DiscoveryClientDocument.References[0] as ContractReference;
            var contract = DiscoveryContractReference.Contract;

            //contract.Types.Schemas.Compile(null, true);

            foreach (DictionaryEntry entry in DiscoveryClient.References)
            {
                if (!(entry.Value is SchemaReference discoveryReference))
                {
                    continue;
                }

                foreach (XmlSchemaObject schemaObject in discoveryReference.Schema.Items)
                {
                    DiscoveryClientReferencesElements.Add(schemaObject);
                }
                //var reference = discoveryReference as SchemaReference;
                //DiscoveryClientReferencesElements.AddRange(reference.Schema.Elements.GetEnumerator().Current);
            }

            messages = contract.Messages as MessageCollection;

            var xmlSchemas = new XmlSchemaSet();
            var ms         = new MemoryStream();
            var writer     = new StringWriter();
            var generator  = new Generator()
            {
                //OutputFolder = "files",
                OutputWriter      = new GeneratorOutput(writer),
                CollectionType    = typeof(System.Collections.Generic.List <>),
                Log               = s => Console.Out.WriteLine(s),
                NamespacePrefix   = nameSpace,
                UseXElementForAny = true,
            };

            var locations = new List <string>();
            var services  = new List <ServiceDescription>();

            foreach (var document in DiscoveryClient.Documents.Values)
            {
                if (document is XmlSchema schema)
                {
                    if (!string.IsNullOrWhiteSpace(schema.SourceUri))
                    {
                        locations.Add(schema.SourceUri);
                    }
                    xmlSchemas.Add(schema);
                }
                else if (document is ServiceDescription service)
                {
                    services.Add(service);
                }
            }

            generator.Generate(locations.ToArray());

            var tree = CSharpSyntaxTree.ParseText(writer.ToString());
            var root = tree.GetRoot();

            var compilationUnit = root as CompilationUnitSyntax;

            if (compilationUnit is null)
            {
                throw new Exception("XmlSchemaClassGenerator did not produce a valid CSharp code file");
            }

            ns = compilationUnit.Members.First() as NamespaceDeclarationSyntax;

            if (ns == null)
            {
                throw new Exception("XmlSchemaClassGenerator did not produce a valid CSharp namespace as the first node");
            }

            foreach (ServiceDescription serviceDescription in services)
            {
                foreach (Binding binding in serviceDescription.Bindings)
                {
                    //currentMessagesList = serviceDescription.Messages.Cast<Message>().ToList();

                    foreach (OperationBinding operationBinding in binding.Operations)
                    {
                        ParseOperationBinding(operationBinding);
                    }
                }
            }

            var newWriter = new StreamWriter("NewSimpleSoapReference.cs", false, Encoding.UTF8);

            ns.NormalizeWhitespace()
            .WriteTo(newWriter);

            newWriter.Flush();
            newWriter.Close();

            return;

            /*xmlSchemas.Compile(null, true);
             *
             * foreach (XmlSchema schema in xmlSchemas)
             * {
             *  foreach (XmlSchemaElement element in schema.Elements.Values)
             *  {
             *      ParseXmlSchemaElement(element);
             *  }
             *
             *  foreach (var value in schema.Items)
             *  {
             *      if (value is XmlSchemaComplexType cType)
             *      {
             *          //ParseXmlSchemaComplexType(cType);
             *      }
             *      else if (value is XmlSchemaSimpleType sType)
             *      {
             *          //ParseXmlSchemaSimpleType(sType);
             *      }
             *  }
             * }
             *
             * var newWriter = new StreamWriter("NewSimpleSoapReference.cs", false, Encoding.UTF8);
             *
             * ns.NormalizeWhitespace()
             *  .WriteTo(newWriter);
             *
             * newWriter.Flush();
             * newWriter.Close();*/
        }
        private async Task <IEndpointResult> ExecuteDiscoDocAsync(HttpContext context)
        {
            _logger.LogTrace("Start discovery request");

            var baseUrl   = _context.GetIdentityServerBaseUrl().EnsureTrailingSlash();
            var allScopes = await _scopes.GetScopesAsync(publicOnly : true);

            var showScopes = new List <Scope>();

            var document = new DiscoveryDocument
            {
                issuer = _context.GetIssuerUri(),
                subject_types_supported = new[] { "public" },
                id_token_signing_alg_values_supported = new[] { Constants.SigningAlgorithms.RSA_SHA_256 }
            };

            // scopes
            if (_options.DiscoveryOptions.ShowIdentityScopes)
            {
                showScopes.AddRange(allScopes.Where(s => s.Type == ScopeType.Identity));
            }
            if (_options.DiscoveryOptions.ShowResourceScopes)
            {
                showScopes.AddRange(allScopes.Where(s => s.Type == ScopeType.Resource));
            }

            if (showScopes.Any())
            {
                document.scopes_supported = showScopes.Where(s => s.ShowInDiscoveryDocument).Select(s => s.Name).ToArray();
            }

            // claims
            if (_options.DiscoveryOptions.ShowClaims)
            {
                var claims = new List <string>();
                foreach (var s in allScopes)
                {
                    claims.AddRange(from c in s.Claims
                                    where s.Type == ScopeType.Identity
                                    select c.Name);
                }

                document.claims_supported = claims.Distinct().ToArray();
            }

            // grant types
            if (_options.DiscoveryOptions.ShowGrantTypes)
            {
                var standardGrantTypes = Constants.SupportedGrantTypes.AsEnumerable();
                if (this._options.AuthenticationOptions.EnableLocalLogin == false)
                {
                    standardGrantTypes = standardGrantTypes.Where(type => type != OidcConstants.GrantTypes.Password);
                }

                var showGrantTypes = new List <string>(standardGrantTypes);

                if (_options.DiscoveryOptions.ShowCustomGrantTypes)
                {
                    showGrantTypes.AddRange(_customGrants.GetAvailableGrantTypes());
                }

                document.grant_types_supported = showGrantTypes.ToArray();
            }

            // response types
            if (_options.DiscoveryOptions.ShowResponseTypes)
            {
                document.response_types_supported = Constants.SupportedResponseTypes.ToArray();
            }

            // response modes
            if (_options.DiscoveryOptions.ShowResponseModes)
            {
                document.response_modes_supported = Constants.SupportedResponseModes.ToArray();
            }

            // token endpoint authentication methods
            if (_options.DiscoveryOptions.ShowTokenEndpointAuthenticationMethods)
            {
                document.token_endpoint_auth_methods_supported = _parsers.GetAvailableAuthenticationMethods().ToArray();
            }

            // endpoints
            if (_options.DiscoveryOptions.ShowEndpoints)
            {
                if (_options.Endpoints.EnableEndSessionEndpoint)
                {
                    document.http_logout_supported = true;
                }

                if (_options.Endpoints.EnableAuthorizeEndpoint)
                {
                    document.authorization_endpoint = baseUrl + Constants.RoutePaths.Oidc.Authorize;
                }

                if (_options.Endpoints.EnableTokenEndpoint)
                {
                    document.token_endpoint = baseUrl + Constants.RoutePaths.Oidc.Token;
                }

                if (_options.Endpoints.EnableUserInfoEndpoint)
                {
                    document.userinfo_endpoint = baseUrl + Constants.RoutePaths.Oidc.UserInfo;
                }

                if (_options.Endpoints.EnableEndSessionEndpoint)
                {
                    document.end_session_endpoint = baseUrl + Constants.RoutePaths.Oidc.EndSession;
                }

                if (_options.Endpoints.EnableCheckSessionEndpoint)
                {
                    document.check_session_iframe = baseUrl + Constants.RoutePaths.Oidc.CheckSession;
                }

                if (_options.Endpoints.EnableTokenRevocationEndpoint)
                {
                    document.revocation_endpoint = baseUrl + Constants.RoutePaths.Oidc.Revocation;
                }

                if (_options.Endpoints.EnableIntrospectionEndpoint)
                {
                    document.introspection_endpoint = baseUrl + Constants.RoutePaths.Oidc.Introspection;
                }
            }

            if (_options.DiscoveryOptions.ShowKeySet)
            {
                if (_options.SigningCertificate != null)
                {
                    document.jwks_uri = baseUrl + Constants.RoutePaths.Oidc.DiscoveryWebKeys;
                }
            }

            return(new DiscoveryDocumentResult(document, _options.DiscoveryOptions.CustomEntries));
        }
Example #19
0
        internal DiscoveryServerType(Type type, string uri) : base(typeof(DiscoveryServerProtocol))
        {
            //
            // parse the uri from a string into a Uri object
            //
            Uri uriObject = new Uri(uri, true);

            //
            // and get rid of the query string if there's one
            //
            uri        = uriObject.GetLeftPart(UriPartial.Path);
            methodInfo = new LogicalMethodInfo(typeof(DiscoveryServerProtocol).GetMethod("Discover", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
            ServiceDescriptionReflector reflector = new ServiceDescriptionReflector();

            reflector.Reflect(type, uri);

            XmlSchemas schemas = reflector.Schemas;

            this.description = reflector.ServiceDescription;

            // We need to force initialization of ServiceDescription's XmlSerializer since we
            // won't necessarily have the permissions to do it when we actually need it
            XmlSerializer serializer = ServiceDescription.Serializer;

            // add imports to the external schemas
            int count = 0;

            foreach (XmlSchema schema in schemas)
            {
                // CONSIDER, erikc, seems fragile/brittle to use the index here in the URL
                if (schema.Id == null || schema.Id.Length == 0)
                {
                    schema.Id = "schema" + (++count).ToString();
                }
                foreach (ServiceDescription description in reflector.ServiceDescriptions)
                {
                    Import import = new Import();
                    import.Namespace = schema.TargetNamespace;
                    import.Location  = uri + "?schema=" + schema.Id;
                    description.Imports.Add(import);
                }
                schemaTable.Add(schema.Id, schema);
            }

            // add imports to the other service descriptions
            for (int i = 1; i < reflector.ServiceDescriptions.Count; i++)
            {
                ServiceDescription description = reflector.ServiceDescriptions[i];
                Import             import      = new Import();
                import.Namespace = description.TargetNamespace;

                // CONSIDER, erikc, seems kinda brittle to use the index of the description
                // as the URL -- when you add interfaces, reorder methods, etc. this might
                // change which could be irritating.
                string id = "wsdl" + i.ToString();

                import.Location = uri + "?wsdl=" + id;
                reflector.ServiceDescription.Imports.Add(import);
                wsdlTable.Add(id, description);
            }

            discoDoc = new DiscoveryDocument();
            discoDoc.References.Add(new ContractReference(uri + "?wsdl", uri));

            foreach (Service service in reflector.ServiceDescription.Services)
            {
                foreach (Port port in service.Ports)
                {
                    SoapAddressBinding soapAddress = (SoapAddressBinding)port.Extensions.Find(typeof(SoapAddressBinding));
                    if (soapAddress != null)
                    {
                        System.Web.Services.Discovery.SoapBinding binding = new System.Web.Services.Discovery.SoapBinding();
                        binding.Binding = port.Binding;
                        binding.Address = soapAddress.Location;
                        discoDoc.References.Add(binding);
                    }
                }
            }
        }
Example #20
0
        private void DownloadWSDL()
        {
            NamespaceDeclarationSyntax ns = NamespaceDeclaration(IdentifierName(nameSpace));

            DiscoveryClientDocument = DiscoveryClient.DiscoverAny(_endpointUri.ToString());

            DiscoveryClient.ResolveAll();
            DiscoveryContractReference = DiscoveryClientDocument.References[0] as ContractReference;

            var schemas = new XmlSchemaSet();

            foreach (DictionaryEntry entry in DiscoveryClient.References)
            {
                if (!(entry.Value is SchemaReference discoveryReference))
                {
                    continue;
                }

                foreach (XmlSchemaObject schemaObject in discoveryReference.Schema.Items)
                {
                    DiscoveryClientReferencesElements.Add(schemaObject);
                }

                schemas.Add(discoveryReference.Schema.TargetNamespace, discoveryReference.Ref);
            }

            var headers = DiscoveryContractReference.Contract.Messages["headers"];

            var ms     = new MemoryStream();
            var writer = new StringWriter();

            var generator = new Generator()
            {
                OutputWriter    = new GeneratorOutput(writer),
                CollectionType  = typeof(System.Collections.Generic.List <>),
                Log             = s => Console.Out.WriteLine(s),
                NamespacePrefix = nameSpace,
                NamingScheme    = NamingScheme.Direct,
                UniqueTypeNamesAcrossNamespaces = true,
                GenerateNullables     = true,
                CollectionSettersMode = CollectionSettersMode.PublicWithoutConstructorInitialization,
                EntityFramework       = true,
                TypeVisitor           = (type, model) =>
                {
                    if ((!type.IsClass) && !(type.IsInterface))
                    {
                        return;
                    }

                    foreach (CodeAttributeDeclaration attribute in type.CustomAttributes)
                    {
                        if (attribute.Name != "System.Xml.Serialization.XmlRootAttribute")
                        {
                            continue;
                        }

                        foreach (CodeAttributeArgument argument in attribute.Arguments)
                        {
                            if (argument.Name != "")
                            {
                                continue;
                            }

                            var partname = (argument.Value as CodePrimitiveExpression).Value.ToString();
                            try
                            {
                                headers.FindPartByName(partname);
                                type.BaseTypes.Add(new CodeTypeReference("SimpleSOAPClient.Models.SoapHeader"));

                                return;
                            }
                            catch { }
                        }
                    }
                }
            };

            generator.Generate(schemas);

            var tree = CSharpSyntaxTree.ParseText(writer.ToString());
            var root = tree.GetRoot();

            if (!(root is CompilationUnitSyntax compilationUnit))
            {
                throw new Exception("XmlSchemaClassGenerator did not produce a valid CSharp code file");
            }

            ns = compilationUnit.Members.First() as NamespaceDeclarationSyntax;

            if (ns == null)
            {
                throw new Exception("XmlSchemaClassGenerator did not produce a valid CSharp namespace as the first node");
            }

            DiscoveryContractReference.Contract.Types.Schemas.Compile(null, true);
            foreach (Binding binding in DiscoveryContractReference.Contract.Bindings)
            {
                var portClass = ClassDeclaration(string.Format("{0}Client", binding.Type.Name)).WithModifiers(TokenList(new[] { Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.PartialKeyword) }));

                foreach (OperationBinding operation in binding.Operations)
                {
                    var inputMessage  = DiscoveryContractReference.Contract.Messages[operation.Input.Name];
                    var outputMessage = DiscoveryContractReference.Contract.Messages[operation.Output.Name];

                    var inputPart  = inputMessage.FindPartByName("parameters");
                    var outputPart = outputMessage.FindPartByName("parameters");

                    var inputElement  = DiscoveryClientReferencesElements.Elements[inputPart.Element.Name];
                    var outputElement = DiscoveryClientReferencesElements.Elements[outputPart.Element.Name];

                    var inputType  = string.Format("{0}.{1}", nameSpace, inputElement.SchemaTypeName.Name);
                    var outputType = string.Format("{0}.{1}", nameSpace, outputElement.SchemaTypeName.Name);

                    var methodName      = QualifiedName(IdentifierName("System.Threading.Tasks"), GenericName(Identifier("Task")).WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList <TypeSyntax>(ParseTypeName(GetAliasedType(outputType))))));
                    var operationMethod = MethodDeclaration(methodName, Identifier(operation.Name));

                    var headerCollectionDeclaration = VariableDeclaration(
                        ArrayType(IdentifierName("SimpleSOAPClient.Models.SoapHeader")).WithRankSpecifiers(
                            SingletonList <ArrayRankSpecifierSyntax>(
                                ArrayRankSpecifier(
                                    SingletonSeparatedList <ExpressionSyntax>(
                                        OmittedArraySizeExpression())))));

                    var headerVariable = VariableDeclarator(Identifier("headers"));

                    var headerArrayInitializer = InitializerExpression(SyntaxKind.ArrayInitializerExpression);

                    SyntaxList <StatementSyntax> bodyStatements = new SyntaxList <StatementSyntax>();

                    foreach (ServiceDescriptionFormatExtension extension in operation.Input.Extensions)
                    {
                        ParameterSyntax parameter;
                        if (extension is SoapHeaderBinding header)
                        {
                            var headerMessage = DiscoveryContractReference.Contract.Messages[header.Message.Name];
                            var headerPart    = headerMessage.FindPartByName(header.Part);
                            var headerElement = DiscoveryClientReferencesElements.Elements[headerPart.Element.Name];
                            var headerType    = string.Format("{0}.{1}", nameSpace, headerElement.SchemaTypeName.Name);
                            parameter = Parameter(Identifier(header.Part)).WithType(ParseTypeName(GetAliasedType(headerType)));

                            operationMethod        = operationMethod.AddParameterListParameters(parameter);
                            headerArrayInitializer = headerArrayInitializer.AddExpressions(IdentifierName(header.Part));
                        }
                        else if (extension is SoapBodyBinding body)
                        {
                            parameter = Parameter(Identifier("request")).WithType(ParseTypeName(GetAliasedType(inputType)));

                            operationMethod = operationMethod.AddParameterListParameters(parameter);
                        }
                    }

                    headerVariable = headerVariable.WithInitializer(EqualsValueClause(headerArrayInitializer));

                    headerCollectionDeclaration = headerCollectionDeclaration.AddVariables(headerVariable);

                    var headerCollectionBlock = LocalDeclarationStatement(headerCollectionDeclaration);

                    bodyStatements = bodyStatements.Add(headerCollectionBlock);
                    bodyStatements = bodyStatements.Add(EmptyStatement().WithSemicolonToken(MissingToken(SyntaxKind.SemicolonToken)));

                    var invocationMemberAccessExpression = MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("SimpleSOAPClient.Models"), IdentifierName("SimpleSOAPClientBase"));

                    var memberAccessExpression = MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, invocationMemberAccessExpression, GenericName(Identifier("Send")).WithTypeArgumentList(TypeArgumentList(SeparatedList <TypeSyntax>(new SyntaxNodeOrToken[] { IdentifierName(GetAliasedType(inputType)), Token(SyntaxKind.CommaToken), IdentifierName(GetAliasedType(outputType)) }))));

                    var arguments = ArgumentList(SeparatedList <ArgumentSyntax>(new SyntaxNodeOrToken[] {
                        Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(operation.Name))), Token(SyntaxKind.CommaToken), Argument(IdentifierName("request")), Token(SyntaxKind.CommaToken), Argument(IdentifierName("headers"))
                    }));

                    var invocationExpression = InvocationExpression(memberAccessExpression).WithArgumentList(arguments);

                    var awaitExpression = AwaitExpression(invocationExpression);

                    bodyStatements = bodyStatements.Add(ReturnStatement(awaitExpression));

                    operationMethod = operationMethod.WithBody(Block(bodyStatements));

                    operationMethod = operationMethod.WithModifiers(new SyntaxTokenList(new SyntaxToken[] { Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.AsyncKeyword) }));

                    portClass = portClass.AddMembers(operationMethod);
                }

                ns = ns.AddMembers(portClass);
            }

            var newWriter = new StreamWriter("NewSimpleSoapReference.cs", false, Encoding.UTF8);

            ns.NormalizeWhitespace()
            .WriteTo(newWriter);

            newWriter.Flush();
            newWriter.Close();
        }
Example #21
0
 public DiscoveryDocumentResult(DiscoveryDocument document, Dictionary <string, object> customEntries)
 {
     Document      = document;
     CustomEntries = customEntries;
 }
        private async Task <IEndpointResult> ExecuteDiscoDocAsync(HttpContext context)
        {
            _logger.LogDebug("Start discovery request");

            if (!_options.Endpoints.EnableDiscoveryEndpoint)
            {
                _logger.LogInformation("Discovery endpoint disabled. 404.");
                return(new StatusCodeResult(404));
            }

            var baseUrl   = context.GetIdentityServerBaseUrl().EnsureTrailingSlash();
            var allScopes = await _scopes.GetEnabledScopesAsync(publicOnly : true);

            var showScopes = new List <Scope>();

            var document = new DiscoveryDocument
            {
                issuer = context.GetIssuerUri(),
                subject_types_supported = new[] { "public" },
                id_token_signing_alg_values_supported = new[] { Constants.SigningAlgorithms.RSA_SHA_256 },
                code_challenge_methods_supported      = new[] { OidcConstants.CodeChallengeMethods.Plain, OidcConstants.CodeChallengeMethods.Sha256 }
            };

            // scopes
            var theScopes = allScopes as Scope[] ?? allScopes.ToArray();

            if (_options.DiscoveryOptions.ShowIdentityScopes)
            {
                showScopes.AddRange(theScopes.Where(s => s.Type == ScopeType.Identity));
            }
            if (_options.DiscoveryOptions.ShowResourceScopes)
            {
                showScopes.AddRange(theScopes.Where(s => s.Type == ScopeType.Resource));
            }

            if (showScopes.Any())
            {
                document.scopes_supported = showScopes.Where(s => s.ShowInDiscoveryDocument).Select(s => s.Name).ToArray();
            }

            // claims
            if (_options.DiscoveryOptions.ShowClaims)
            {
                var claims = new List <string>();
                foreach (var s in theScopes)
                {
                    claims.AddRange(from c in s.Claims
                                    where s.Type == ScopeType.Identity
                                    select c.Name);
                }

                document.claims_supported = claims.Distinct().ToArray();
            }

            // grant types
            if (_options.DiscoveryOptions.ShowGrantTypes)
            {
                var standardGrantTypes = new List <string>
                {
                    OidcConstants.GrantTypes.AuthorizationCode,
                    OidcConstants.GrantTypes.ClientCredentials,
                    OidcConstants.GrantTypes.RefreshToken,
                    OidcConstants.GrantTypes.Implicit
                };

                if (!(_resourceOwnerValidator is NotSupportedResouceOwnerPasswordValidator))
                {
                    standardGrantTypes.Add(OidcConstants.GrantTypes.Password);
                }

                var showGrantTypes = new List <string>(standardGrantTypes);

                if (_options.DiscoveryOptions.ShowExtensionGrantTypes)
                {
                    showGrantTypes.AddRange(_extensionGrants.GetAvailableGrantTypes());
                }

                document.grant_types_supported = showGrantTypes.ToArray();
            }

            // response types
            if (_options.DiscoveryOptions.ShowResponseTypes)
            {
                document.response_types_supported = Constants.SupportedResponseTypes.ToArray();
            }

            // response modes
            if (_options.DiscoveryOptions.ShowResponseModes)
            {
                document.response_modes_supported = Constants.SupportedResponseModes.ToArray();
            }

            // token endpoint authentication methods
            if (_options.DiscoveryOptions.ShowTokenEndpointAuthenticationMethods)
            {
                document.token_endpoint_auth_methods_supported = _parsers.GetAvailableAuthenticationMethods().ToArray();
            }

            // endpoints
            if (_options.DiscoveryOptions.ShowEndpoints)
            {
                if (_options.Endpoints.EnableAuthorizeEndpoint)
                {
                    document.authorization_endpoint = baseUrl + Constants.ProtocolRoutePaths.Authorize;
                }

                if (_options.Endpoints.EnableTokenEndpoint)
                {
                    document.token_endpoint = baseUrl + Constants.ProtocolRoutePaths.Token;
                }

                if (_options.Endpoints.EnableUserInfoEndpoint)
                {
                    document.userinfo_endpoint = baseUrl + Constants.ProtocolRoutePaths.UserInfo;
                }

                if (_options.Endpoints.EnableEndSessionEndpoint)
                {
                    document.frontchannel_logout_session_supported = true;
                    document.frontchannel_logout_supported         = true;
                    document.end_session_endpoint = baseUrl + Constants.ProtocolRoutePaths.EndSession;
                }

                if (_options.Endpoints.EnableCheckSessionEndpoint)
                {
                    document.check_session_iframe = baseUrl + Constants.ProtocolRoutePaths.CheckSession;
                }

                if (_options.Endpoints.EnableTokenRevocationEndpoint)
                {
                    document.revocation_endpoint = baseUrl + Constants.ProtocolRoutePaths.Revocation;
                }

                if (_options.Endpoints.EnableIntrospectionEndpoint)
                {
                    document.introspection_endpoint = baseUrl + Constants.ProtocolRoutePaths.Introspection;
                }
            }

            if (_options.DiscoveryOptions.ShowKeySet)
            {
                if ((await _keys.GetValidationKeysAsync()).Any())
                {
                    document.jwks_uri = baseUrl + Constants.ProtocolRoutePaths.DiscoveryWebKeys;
                }
            }

            return(new DiscoveryDocumentResult(document, _options.DiscoveryOptions.CustomEntries));
        }
Example #23
0
    public override void WriteDocument(object document, System.IO.Stream stream)
    {
        DiscoveryDocument myDiscoveryDocument = (DiscoveryDocument)document;

        myDiscoveryDocument.Write(stream);
    }
Example #24
0
        static async void onAuthorized(object sender, AuthResultEventArgs args)
        {
            await DiscoveryDocument.TryDownloadAndSetCurrent(args.Result.Value, true);

            // obsolete AuthScope.Discover(discoDocumentDownloaded.Value);
        }