Export (0) Print
Expand All

List Service Certificates

Updated: September 30, 2014

The List Service Certificates operation lists all of the service certificates associated with the specified cloud service.

The List Service Certificates request may be specified as follows. Replace <subscription-id> with the subscription ID, and <service-name> with the name of the cloud service.

 

Method Request URI

GET

https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-DNS-name>/certificates

You must make sure that the request that is made to the management service is secure. For additional details, see Authenticating Service Management Requests.

The following table describes the request headers.

 

Request Header Description

x-ms-version

Required. Specifies the version of the operation to use for this request. This header should be set to 2009-10-01 or a higher. For more information about versioning headers, see Service Management Versioning.

The response includes an HTTP status code, a set of response headers, and a response body.

A successful operation returns status code 200 (OK). For information about status codes, see Service Management Status and Error Codes.

The response for this operation includes the following headers. The response may also include additional standard HTTP headers. All standard headers comply with the HTTP/1.1 protocol specification.

 

Response Header Description

x-ms-request-id

A value that uniquely identifies a request made against the management service.

The format of the response body is as follows:


<?xml version="1.0" encoding="utf-8"?>
  <Certificates xmlns=”http://schemas.microsoft.com/windowsazure”>
    <Certificate>
      <CertificateUrl>certificate-thumbprint-address</CertificateUrl>
      <Thumbprint>certificate-thumbprint</Thumbprint>
      <ThumbprintAlgorithm>thumbprint-algorithm</ThumbprintAlgorithm>        
      <Data>base64-encoded-X509-representation-of-the-certificate</Data>
    </Certificate>
  </Certificates>

The following table describes the elements of the response body.

 

Element name Description

CertificateUrl

The Service Management API request URI used to perform Get Service Certificate requests against the certificate store.

Thumbprint

The X509 certificate thumb print property of the service certificate.

ThumbprintAlgorithm

The algorithm that was used to hash the service certificate. Currently SHA-1 is the only supported algorithm.

Data

The public part of the service certificate as a base-64 encoded .cer file.

The following console program lists the cloud services created in the specified subscription, and then lists the certificates associated with each cloud service, if any. To run the example, update the Version string with the desired value to use in the x-ms-version header, change the Thumbprint value to the thumbprint of your management certificate, and change the SubscriptionId to your subscription identifier value.

namespace Microsoft.WindowsAzure.ServiceManagementRESTAPI.Samples
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    using System.Xml;
    using System.Xml.Linq;
 
    public class Program
    {
        // Set these constants with your values to run the sample.
        private const string Version = "2011-10-01";
        private const string Thumbprint = "management-certificate-thumbprint";
        private const string SubscriptionId = "subscription-identifier";
 
        // This is the common namespace for all Service Management REST API XML data.
        private static XNamespace wa = "http://schemas.microsoft.com/windowsazure";
 
        /// <summary>
        /// Gets or sets the certificate that matches the Thumbprint value.
        /// </summary>
        private static X509Certificate2 Certificate { getset; }
 
        static void Main(string[] args)
        {
            try
            {
                Certificate = GetCertificate(Thumbprint);
 
                // Display the hosted services in the subscription.
                XElement hostedServices = ListHostedServices();
                Console.WriteLine(
                    "Hosted Services for Subscription ID {0}:{1}{2}",
                    SubscriptionId,
                    Environment.NewLine,
                    hostedServices.ToString(SaveOptions.OmitDuplicateNamespaces));
 
                // Display the certificates associated with each hosted
                // service, if any.
                foreach (XElement hostedService in 
                    hostedServices.Elements(wa + "HostedService"))
                {
                    string serviceName = 
                        hostedService.Element(wa + "ServiceName").Value;
                    XElement certificates = ListCertificates(serviceName);
                    Console.WriteLine(
                        "Certificates for Hosted Service {0}:{1}{2}",
                        serviceName,
                        Environment.NewLine,
                        certificates.ToString(SaveOptions.OmitDuplicateNamespaces));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught in Main:");
                Console.WriteLine(ex.Message);
            }
 
            Console.Write("Press any key to continue:");
            Console.ReadKey();
        }
 
        /// <summary>
        /// Calls the List Hosted Services operation in the Service Management 
        /// REST API for the specified subscription and returns the 
        /// HostedServices XML element from the response.
        /// </summary>
        /// <returns>The HostedServices XML element from the response.</returns>
        private static XElement ListHostedServices()
        {
            string uriFormat = "https://management.core.windows.net/{0}" +
                "/services/hostedservices";
            Uri uri = new Uri(String.Format(uriFormat, SubscriptionId));
            XDocument responseBody;
            InvokeRequest(uri, "GET", HttpStatusCode.OK, nullout responseBody);
            return responseBody.Element(wa + "HostedServices");
        }
 
        /// <summary>
        /// Calls the List Certificates operation in the Service Management 
        /// REST API for the specified subscription and hosted service, and 
        /// returns the Certificates XML element from the response.
        /// </summary>
        /// <param name="serviceName">The hosted service name to list certificates for.</param>
        /// <returns>The HostedServices XML element from the response.</returns>
        private static XElement ListCertificates(
            string serviceName)
        {
            string uriFormat = "https://management.core.windows.net/{0}" +
                "/services/hostedservices/{1}/certificates";
            Uri uri = new Uri(String.Format(uriFormat, SubscriptionId, serviceName));
            XDocument responseBody;
            InvokeRequest(uri, "GET", HttpStatusCode.OK, nullout responseBody);
            return responseBody.Element(wa + "Certificates");
        }
 
        /// <summary>
        /// Gets the certificate matching the thumbprint from the local store.
        /// Throws an ArgumentException if a matching certificate is not found.
        /// </summary>
        /// <param name="thumbprint">The thumbprint of the certificate to find.</param>
        /// <returns>The certificate with the specified thumbprint.</returns>
        private static X509Certificate2 GetCertificate(string thumbprint)
        {
            List<StoreLocation> locations = new List<StoreLocation> 
            { 
                StoreLocation.CurrentUser, 
                StoreLocation.LocalMachine 
            };
 
            foreach (var location in locations)
            {
                X509Store store = new X509Store("My", location);
                try
                {
                    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                    X509Certificate2Collection certificates = store.Certificates.Find(
                        X509FindType.FindByThumbprint, thumbprint, false);
                    if (certificates.Count == 1)
                    {
                        return certificates[0];
                    }
                }
                finally
                {
                    store.Close();
                }
            }
 
            throw new ArgumentException(string.Format(
                "A Certificate with Thumbprint '{0}' could not be located.",
                thumbprint));
        }
 
        /// <summary>
        /// A helper function to invoke a Service Management REST API operation.
        /// Throws an ApplicationException on unexpected status code results.
        /// </summary>
        /// <param name="uri">The URI of the operation to invoke using a web request.</param>
        /// <param name="method">The method of the web request, GET, PUT, POST, or DELETE.</param>
        /// <param name="expectedCode">The expected status code.</param>
        /// <param name="requestBody">The XML body to send with the web request. Use null to send no request body.</param>
        /// <param name="responseBody">The XML body returned by the request, if any.</param>
        /// <returns>The requestId returned by the operation.</returns>
        private static string InvokeRequest(
            Uri uri,
            string method,
            HttpStatusCode expectedCode,
            XDocument requestBody,
            out XDocument responseBody)
        {
            responseBody = null;
            string requestId = String.Empty;
 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            request.Method = method;
            request.Headers.Add("x-ms-Version", Version);
            request.ClientCertificates.Add(Certificate);
            request.ContentType = "application/xml";
 
            if (requestBody != null)
            {
                using (Stream requestStream = request.GetRequestStream())
                {
                    using (StreamWriter streamWriter = new StreamWriter(
                        requestStream, System.Text.UTF8Encoding.UTF8))
                    {
                        requestBody.Save(streamWriter, SaveOptions.DisableFormatting);
                    }
                }
            }
 
            HttpWebResponse response;
            HttpStatusCode statusCode = HttpStatusCode.Unused;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                // GetResponse throws a WebException for 4XX and 5XX status codes
                response = (HttpWebResponse)ex.Response;
            }
 
            try
            {
                statusCode = response.StatusCode;
                if (response.ContentLength > 0)
                {
                    using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))
                    {
                        responseBody = XDocument.Load(reader);
                    }
                }
 
                if (response.Headers != null)
                {
                    requestId = response.Headers["x-ms-request-id"];
                }
            }
            finally
            {
                response.Close();
            }
 
            if (!statusCode.Equals(expectedCode))
            {
                throw new ApplicationException(string.Format(
                    "Call to {0} returned an error:{1}Status Code: {2} ({3}):{1}{4}",
                    uri.ToString(),
                    Environment.NewLine,
                    (int)statusCode,
                    statusCode,
                    responseBody.ToString(SaveOptions.OmitDuplicateNamespaces)));
            }
 
            return requestId;
        }
    }
}

This code will print something that resembles the following example output for a hosted service that has one associated certificate:

Hosted Services for Subscription ID 01234567-89ab-cdef-0123-456789abcdef:
<HostedServices xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <HostedService>
    <Url>https://management.core.windows.net/01234567-89ab-cdef-0123-456789abcdef/services/hostedservices/MyHostedService1</Url>
    <ServiceName>MyHostedService1</ServiceName>
  </HostedService>
</HostedServices>
Certificates for Hosted Service MyHostedService1:
<Certificates xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Certificate>
    <CertificateUrl>https://management.core.windows.net/01234567-89ab-cdef-0123-456789abcdef/services/hostedservices/MyHostedService1/certificates/sha1-FF4BA7635E51B0A41B39424287158E210F875EFE</CertificateUrl>
    <Thumbprint>FF4BA7635E51B0A41B39424287158E210F875EFE</Thumbprint>
    <ThumbprintAlgorithm>sha1</ThumbprintAlgorithm>
    <Data>MIIDFzCCAgOgAwIBAgIQVNJIs1lMC7FAvxwK4Jki+DAJBgUrDgMCHQUAMCAxHjAcBgNVBAMTFWFkYXNoY29saW5ybWFuYWdlbWVudDAeFw0xMTA5MDkxOTM2MzJaFw0zOTEyMzEyMzU5NTlaMCAxHjAcBgNVBAMTFWFkYXNoY29saW5ybWFuYWdlbWVudDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANd/qnw5Gn986t8HLzg6A9ztyYrU9x0KTxTgPrfYui7OqSwh1oyAvRigkrxMFRwgLmY+V9AX6NQf1P6pOCxgH44qVaskjlFCNGVZBhzcS1Q+h81R6g31XjdXYj8L2jzXFBee2wEGPpqqC/x+eaTJ7LDQdWUk7lL4XMR14bN6oQ0xGKwF1OXSN+bl50xzbqUIHFXIVFqM7WJ+WVWTDUTwByGFQ8MFQIyi3CvU0yZEAWZeF3rKbl+ZBqnfHxJZxCk85it5+sY8DnCBDb8+W5gWPQBI8xfit364Mc/PO1e0HKIaJqZqRxE1dJme/nh7UZuR9lrheD0Jz5+C0L1NUnE237cCAwEAAaNVMFMwUQYDVR0BBEowSIAQ5qqyjL/fzailNzIac9amXqEiMCAxHjAcBgNVBAMTFWFkYXNoY29saW5ybWFuYWdlbWVudIIQVNJIs1lMC7FAvxwK4Jki+DAJBgUrDgMCHQUAA4IBAQDRWho2t4tpeNUBKwuSr+Bq11nX3nNCILSeg/FPujCLSc3D7rlo1Galqc/8Fuq2+9xN5o+ziJxnhL7LJcTw0BS6PQ8fdqRScmZL4EgSzyorlF6YpW926JAfxcbPvootZvFyzP9eM5zXg0YWD4XVYXq/xME1TR2UJ8Sf59leVdfeTbHhcJiU89O0w/EDLTCWir66+e8MnzHZzyQO/MHLIpB9rY510XXeWZ/t7JYDXmv1CM6uRaS0oflGN+rizOeiRB4wQRsKwLDTQFcQ1tX6EXX2BTPBbrs2tMbi+KyWtTMDmHaiACjqbrEznNcUqOQ62JxKwpD5BDicsMwcOjWYkKBo</Data>
  </Certificate>
</Certificates>
Press any key to continue:

Show:
© 2014 Microsoft