Повторное создание ключей учетной записи хранения

 

Regenerate Keys Асинхронную операцию, повторно создает первичный или вторичный ключ доступа для указанной учетной записи хранилища.

Запрос

Regenerate Keys Можно составить следующим образом. Замените <subscription-id> своим Идентификатором подписки и <service-name> с именем нужной учетной записи хранения.

Метод URI запроса
POST https://management.core.windows.net/<subscription-id>/services/storageservices/<service-name>/keys?action=regenerate

Необходимо убедиться, что запрос к службе управления безопасен. Дополнительные сведения см. в разделе Проверка подлинности запросов управления службами.

Параметры URI

Параметр URI Описание
action=regenerate Обязательно. Указывает, что следует заново создать первичный или вторичный ключ доступа для указанной учетной записи хранения.

Заголовки запроса

В следующей таблице описаны заголовки запросов.

Заголовок запроса Описание
Content-Type Обязательно. Задайте для этого заголовка application/xml.
x-ms-version Обязательно. Задает версию операции, используемой для этого запроса. Этот заголовок должен быть установлен 2009-10-01 или более поздней версии. Дополнительные сведения об управлении версиями заголовков см. в разделе Управление версиями службы управления.

Текст запроса

Текст запроса указывает, какой ключ следует создать повторно — первичный или вторичный. Далее приведен формат текста запроса.

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

В следующей таблице описываются элементы текста запроса.

Имя элемента Описание
KeyType Указывает, какой ключ следует создать повторно. Допустимые значения:

- Первичный
- Вторичный

Ответ

Ответ включает код состояния HTTP, набор заголовков ответа и текст ответа.

Код состояния

Успешная операция возвращает код состояния 200 (ОК). Сведения о кодах состояния см. в разделе состояние службы управления и коды ошибок.

Заголовки ответа

Ответ для этой операции включает следующие заголовки. Ответ может также включать дополнительные стандартные заголовки HTTP. Все стандартные заголовки соответствуют спецификации протокола HTTP/1.1.

Заголовок ответа Описание
x-ms-request-id Значение, которое однозначно определяет запрос к службе управления. Для асинхронной операции можно вызвать Получение состояния операции со значением заголовка, чтобы определить, завершена ли операция, произошел ли сбой, или она все еще выполняется.

Текст ответа

Ответ возвращает как первичный, так и вторичный ключ доступа. Текст ответа имеет следующий формат:

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

В следующей таблице описаны элементы текста ответа.

Имя элемента Описание
URL-адрес Запрос API управления службами, используемый URI для выполнения Получение свойств учетной записи хранения запросов к учетной записи хранилища.
Первичный Первичный ключ для указанной учетной записи хранения.
Вторичный Вторичный ключ для указанной учетной записи хранения.

Примечания

Regenerate Storage Account Keys Операция вызывает первичного или вторичного ключа для учетной записи службы хранилища должен создаваться повторно. Эта операция может использоваться с учетными записями хранения, возвращенный Список учетных записей хранилища операции для автоматизации управления обновлениями ключей хранилища.

Пример

В следующем примере программа принимает идентификатор подписки, связанный отпечаток сертификата управления, строку версии операции, имя учетной записи хранения и выводит возвращенные ключи доступа для учетной записи хранения на консоль. Затем он вызывает Regenerate Storage Account Keys операции, чтобы заново создать вторичный ключ доступа для учетной записи хранилища и печатает результаты для новых ключей. Инициализация Version константы со строкой заголовка версии, SubscriptionId с идентификатором GUID для подписки, Thumbprint с вашей значение отпечатка сертификата управления и ServiceName с именем учетной записи для запуска примера кода.

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 = "https://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; } } }  
  

Этот пример программы формирует результаты примерно следующего вида:

Storage Account Keys for myexamplestorage1: <StorageService xmlns="https://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="https://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: