gpt4 book ai didi

azure - 为什么我使用 Azure 服务管理 API 收到 403 错误?

转载 作者:行者123 更新时间:2023-12-02 06:40:42 28 4
gpt4 key购买 nike

我想使用 Azure API 管理 (management.core.windows.net) 重新启动角色实例(请参阅 Microsoft 文档: https://learn.microsoft.com/en-us/rest/api/compute/cloudservices/rest-reboot-role-instance ),但我收到 403 作为回应。

请求:

https://management.core.windows.net/{subscription-id}/services/hostedservices/{hosted-service}/deploymentslots/staging/roleinstances/{role-instance-name}?comp=reboot`

Headers:
- Authorization: Bearer {token}
- Content-Type: application/xml
- x-ms-version: 2010-10-28
- Content-Length: 0

Body: Empty

响应正文:

<Error xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Code>ForbiddenError</Code>
<Message>The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.</Message>
</Error>

我通过调用获取身份验证 - 承载 token (请参阅 Microsoft 文档: https://learn.microsoft.com/en-us/azure/active-directory/azuread-dev/v1-oauth2-client-creds-grant-flow#service-to-service-access-token-request ):

https://login.microsoftonline.com/{tenant_id}/oauth2/token

Headers:
- Content-Type: application/x-www-form-urlencoded

Body:
- grant_type: client_credentials,
- client_id: {client_id}
- client_secret: {client_secret}
- resource: https://management.core.windows.net/

有什么想法吗?请求端或 Azure 门户端是否缺少配置?因为我可以使用 management.azure.com,所以 management.core.windows.net 是否已弃用?

注释:

  • 我已经在 Azure 端配置了权限:我为此创建了一个应用注册,并使用一个 secret 来授予作为贡献者的权限;
  • management.azure.com API 使用承载 token 。我可以访问其他资源,例如 https://management.azure.com/subscriptions/{subscription-id}/resourcegroups?api-version=2017-05-10,但无法访问https://management.core.windows.net/{subscription-id}/services/hostedservices 资源。
  • 我正在 Postman 上对此进行测试。
<小时/>

解决方案

问题与证书配置有关

$cert = New-SelfSignedCertificate -Subject "CN=Azure Management API" -CertStoreLocation "cert:\LocalMachine\My" -KeyLength 2048 -KeySpec "KeyExchange" -NotAfter (Get-Date).AddMonths(360)
$password = ConvertTo-SecureString -String "strong-password-here" -Force -AsPlainText
Export-PfxCertificate -Cert $cert -FilePath ".\azure-management-api.pfx" -Password $password
Export-Certificate -Type CERT -Cert $cert -FilePath .\azure-management-api.cer

注意证书是.pfx的重要性

代码

   var cert = new X509Certificate2( File.ReadAllBytes( "your-certificate-path.pfx" ), "your_password" );
var httpClientHandler = new HttpClientHandler
{
UseProxy = false,
ClientCertificateOptions = ClientCertificateOption.Manual
};
httpClientHandler.ClientCertificates.Add( cert );
var httpClient = new HttpClient( httpClientHandler );
httpClient.DefaultRequestHeaders.Add( "Accept", "application/xml" );
httpClient.DefaultRequestHeaders.Add( "Host", "management.core.windows.net" );
httpClient.DefaultRequestHeaders.Add( "x-ms-version", "2010-10-28" );
var uri = $"https://management.core.windows.net/{subscriptionId}/services/hostedservices";
Console.WriteLine( $"GET {uri} [{httpClient.DefaultRequestVersion}]" );
foreach ( var header in httpClient.DefaultRequestHeaders )
{
Console.WriteLine( $"{header.Key} {header.Value.First()}" );
}
var response = httpClient.GetAsync( uri )
.GetAwaiter()
.GetResult();
var content = response.Content.ReadAsStringAsync()
.GetAwaiter()
.GetResult();
Console.WriteLine( $"{(int)response.StatusCode} {response.StatusCode}" );
Console.WriteLine( content );
httpClient.Dispose();
httpClientHandler.Dispose();

最佳答案

根据您的描述,您想要管理Azure云服务。 Azure云服务是Azure classic resource 。所以我们需要使用Azure服务管理API来管理它。如果我们要调用API,我们需要进行X509客户端证书认证。更多详情请引用document

详细步骤如下

  1. 将证书上传到 AzureA。创建证书

    $cert = New-SelfSignedCertificate -DnsName yourdomain.cloudapp.net -CertStoreLocation "cert:\LocalMachine\My" -KeyLength 2048 -KeySpec "KeyExchange"
    $password = ConvertTo-SecureString -String "your-password" -Force -AsPlainText
    Export-PfxCertificate -Cert $cert -FilePath ".\my-cert-file.pfx" -Password $password
    Export-Certificate -Type CERT -Cert $cert -FilePath .\my-cert-file.cer

    b 将 .cer 文件上传到 Azure(订阅 -> 您的订阅 -> 管理证书) enter image description here

  2. 代码(例如,我在订阅中列出了云服务)

 static async Task Main(string[] args)
{
var _clientHandler = new HttpClientHandler();
_clientHandler.ClientCertificates.Add(GetStoreCertificate("the cert's thumbprint" ));
_clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
String uri = string.Format("https://management.core.windows.net/{0}/services/hostedservices", "subscription id");
using (var _client = new HttpClient(_clientHandler))
using (var request = new HttpRequestMessage(HttpMethod.Get, uri)) {

request.Headers.Add("x-ms-version", "2014-05-01");
request.Headers.Add("Accept", "application/xml");
//request.Headers.Add("Content-Type", "application/xml");
using (HttpResponseMessage httpResponseMessage = await _client.SendAsync(request)) {
string xmlString = await httpResponseMessage.Content.ReadAsStringAsync();
Console.WriteLine(httpResponseMessage.StatusCode);
Console.WriteLine(xmlString);
}

}
}
private static X509Certificate2 GetStoreCertificate(string thumbprint)
{


X509Store store = new X509Store("My", StoreLocation.LocalMachine);
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));
}

enter image description here

关于azure - 为什么我使用 Azure 服务管理 API 收到 403 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63374169/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com