Eksportuj (0) Drukuj
Rozwiń wszystko
EN
Ta zawartość nie jest dostępna w wymaganym języku. Wersja w języku angielskim znajduje się tutaj.

Regenerate Storage Account Keys

Updated: September 30, 2014

The Regenerate Keys asynchronous operation regenerates the primary or secondary access key for the specified storage account.

The Regenerate Keys request may be specified as follows. Replace <subscription-id> with your subscription ID, and <service-name> with the name of the desired storage account.

 

Method Request URI

POST

https://management.core.windows.net/<subscription-id>/services/storageservices/<service-name>/keys?action=regenerate

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

 

URI Parameter Description

action=regenerate

Required. Specifies that the primary or secondary access key for the specified storage account must be regenerated.

The following table describes the request headers.

 

Request Header Description

Content-Type

Required. Set this header to application/xml.

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 higher. For more information about versioning headers, see Service Management Versioning.

The request body indicates which key to regenerate, the primary key or the secondary key. The format of the request body is as follows:


<?xml version="1.0" encoding="utf-8"?>
<RegenerateKeys xmlns="http://schemas.microsoft.com/windowsazure">
  <KeyType>Primary|Secondary</KeyType>
</RegenerateKeys>

The following table describes the elements of the request body.

 

Element Name Description

KeyType

Specifies which key to regenerate. Valid values are:

  • Primary

  • Secondary

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 conform to 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. For an asynchronous operation, you can call Get Operation Status with the value of the header to determine whether the operation is complete, has failed, or is still in progress.

The response returns both the primary and secondary access keys. The format of the response body is as follows:


<?xml version="1.0" encoding="utf-8"?>
  <StorageService xmlns="http://schemas.microsoft.com/windowsazure">
    <Url>storage-service-request-uri</Url>
    <StorageServiceKeys>
      <Primary>primary-key</Primary>
      <Secondary>secondary-key</Secondary>
    </StorageServiceKeys>
  </StorageService>

The following table describes the elements of the response body.

 

Element Name Description

Url

The Service Management API request URI used to perform Get Storage Account Properties requests against the storage account.

Primary

The primary key for the specified storage account.

Secondary

The secondary key for the specified storage account.

The Regenerate Storage Account Keys operation causes the Primary or Secondary key for a storage account service to be regenerated. This operation can be used with the storage accounts returned by the List Storage Accounts operation, to automate management of storage key updates.

The following example program takes the subscription ID, an associated management certificate thumbprint, the operation version string, and a storage account name, and prints the returned storage account access keys to the console. It then calls the Regenerate Storage Account Keys operation to regenerate the Secondary access key for the storage account, and prints the new key results. Initialize the Version constant with a version header string, SubscriptionId with the GUID identifier for the subscription, Thumbprint with your management certificate thumbprint value, and ServiceName with the name of your storage account to run the example code.

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-id-guid";
        private const string ServiceName = "storage-account-name";
 
        // 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 { get; set; }
 
        static void Main(string[] args)
        {
            try
            {
                Certificate = GetCertificate(Thumbprint);
 
                XElement initialKeys = 
                    GetStorageAccountKeys(SubscriptionId, ServiceName);
                Console.WriteLine(
                    "Storage Account Keys for {0}:{1}{2}",
                    ServiceName, 
                    Environment.NewLine,
                    initialKeys.ToString(SaveOptions.OmitDuplicateNamespaces));
 
                string keyType = "Secondary";
                XElement regeneratedKeys =
                    RegenerateStorageAccountKeys(SubscriptionId, ServiceName, keyType);
                Console.WriteLine(
                    "Regenerated {0} Storage Account Key for {1}:{2}{3}",
                    keyType, 
                    ServiceName, 
                    Environment.NewLine,
                    regeneratedKeys.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>
        /// 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>
        /// Calls the Get Storage Account Keys operation in the Service Management
        /// REST API for the specified subscription and storage account name and returns
        /// the StorageService XML element from the response.
        /// </summary>
        /// <param name="subscriptionId">The subscription identifier.</param>
        /// <param name="serviceName">The name of the storage account.</param>
        /// <returns>The StorageService XML element from the response.</returns>
        private static XElement GetStorageAccountKeys(
            string subscriptionId,
            string serviceName)
        {
            string uriFormat = "https://management.core.windows.net/{0}" +
                "/services/storageservices/{1}/keys";
            Uri uri = new Uri(String.Format(uriFormat, subscriptionId, serviceName));
            XDocument responseBody;
            string requestId;
            HttpStatusCode statusCode = 
                InvokeRequest(uri, "GET", null, out responseBody, out requestId);
            VerifyResult(uri, statusCode, HttpStatusCode.OK, responseBody);
            return responseBody.Element(wa + "StorageService");
        }
 
        /// <summary>
        /// Calls the Regenerate Storage Account Keys operation in the Service 
        /// Management REST API for the specified subscription, storage account name, 
        /// and key, and returns the StorageService XML element from the response.
        /// </summary>
        /// <param name="subscriptionId">The subscription identifier.</param>
        /// <param name="serviceName">The name of the storage account.</param>
        /// <param name="keyType">A value of "Primary" or "Secondary" to specify the key to regenerate.</param>
        /// <returns>The StorageService XML element from the response.</returns>
        private static XElement RegenerateStorageAccountKeys(
            string subscriptionId,
            string serviceName,
            string keyType)
        {
            string uriFormat = "https://management.core.windows.net/{0}" +
                "/services/storageservices/{1}/keys?action=regenerate";
            Uri uri = new Uri(String.Format(uriFormat, subscriptionId, serviceName));
            XDocument requestBody = new XDocument(
                new XDeclaration("1.0", "UTF-8", "no"),
                new XElement(
                    wa + "RegenerateKeys",
                    new XElement(wa + "KeyType", keyType)));
            XDocument responseBody;
            string requestId;
            HttpStatusCode statusCode =
                InvokeRequest(uri, "POST", requestBody, out responseBody, out requestId);
            VerifyResult(uri, statusCode, HttpStatusCode.OK, responseBody);
            return responseBody.Element(wa + "StorageService");
        }
 
        /// <summary>
        /// A helper function to invoke a Service Management REST API operation.
        /// </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="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>
        /// <param name="requestId">The requestId returned by the request, if any.</param>
        /// <returns>The status code returned by the request.</returns>
        private static HttpStatusCode InvokeRequest(
            Uri uri,
            string method,
            XDocument requestBody,
            out XDocument responseBody,
            out string requestId)
        {
            responseBody = null;
            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();
            }
 
            return statusCode;
        }
 
        /// <summary>
        /// A helper function to throw an ApplicationException on unexpected 
        /// status code responses from Service Management REST API operation calls.
        /// </summary>
        /// <param name="uri">The URI of the Service Management operation.</param>
        /// <param name="statusCode">The status code returned by the operation.</param>
        /// <param name="expectedCode">The expected status code.</param>
        /// <param name="responseBody">The response body returned by the operation.</param>
        private static void VerifyResult(
            Uri uri,
            HttpStatusCode statusCode,
            HttpStatusCode expectedCode,
            XDocument responseBody)
        {
            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;
        }
    }
}

This example program generates results similar to the following:

Storage Account Keys for myexamplestorage1:
<StorageService xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Url>https://management.core.windows.net/01234567-89ab-cdef-0123-456789abcdef/services/storageservices/myexamplestorage1</Url>
  <StorageServiceKeys>
    <Primary>XrmGWqu6qpgKX5G3lf+V5Bc0nFIGjGWiWhHTdMxkA5Mb4WjJ0rDV+3USWW/9fAWCrszrkr8+JUb1c5mxQdq4nw==</Primary>
    <Secondary>7jGHqUXHfASoUWeuClG9TXRZ59tTl5Fep8BNi5f86LFuewc0dQjDc6pyyju8BOi5947byrtgKnVtYO4f4cVdcg==</Secondary>
  </StorageServiceKeys>
</StorageService>
Regenerated Secondary Storage Account Key for myexamplestorage1:
<StorageService xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Url>https://management.core.windows.net/01234567-89ab-cdef-0123-456789abcdef/services/storageservices/myexamplestorage1</Url>
  <StorageServiceKeys>
    <Primary>XrmGWqu6qpgKX5G3lf+V5Bc0nFIGjGWiWhHTdMxkA5Mb4WjJ0rDV+3USWW/9fAWCrszrkr8+JUb1c5mxQdq4nw==</Primary>
    <Secondary>2Wd7lP3MesbkFi0LAltwUd40L6uu85N9VBtokOo2RfpqKA8q39orkJ6WUV3jP4TkZuYrSQNYxkQ5axcSzzTu8A==</Secondary>
  </StorageServiceKeys>
</StorageService>
Press any key to continue:

Pokaż:
© 2014 Microsoft