gpt4 book ai didi

c# - Azure 计费使用 API 返回 401 未经授权

转载 作者:太空狗 更新时间:2023-10-29 21:56:59 25 4
gpt4 key购买 nike

我正在使用 Azure REST API 来获取计费使用情况和费率卡详细信息。要使用 AcquireToken() 方法获取 token ,最初我仅使用客户端 ID,然后在登录窗口中请求用户凭据。

但是,我正在寻找非交互式方法,因此我使用了客户端凭据,其中传递了客户端 ID客户端 key

但它给出“远程服务器返回错误 401 未经授权”

当我深入研究错误时,我发现它给出错误“访问 token 来自错误的受众或资源”

请给我任何解决方案,让我无需任何用户交互即可访问 API。

提前致谢。

这是我的代码:

{
string token = GetOAuthTokenFromAAD();
string requestURL = String.Format("{0}/{1}/{2}/{3}",
ConfigurationManager.AppSettings["ARMBillingServiceURL"],
"subscriptions",
ConfigurationManager.AppSettings["SubscriptionID"],
"providers/Microsoft.Commerce/RateCard?api-version=2015-06-01-preview&$filter=OfferDurableId eq 'MS-AZR-*****' and Currency eq 'INR' and Locale eq 'en-IN' and RegionInfo eq 'IN'");

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);

request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(String.Format("RateCard service response status: {0}", response.StatusDescription));
}

public static string GetOAuthTokenFromAAD()
{
AuthenticationContext authenticationContext = new AuthenticationContext(string.Format("{0}/{1}",ConfigurationManager.AppSettings["ADALServiceURL"], ConfigurationManager.AppSettings["TenantDomain"]));

AuthenticationResult result = null;
ClientCredential uc = new ClientCredential(Client_Id, Secret_Key);
try
{
result = authenticationContext.AcquireToken("https://management.core.windows.net/", uc);
}
return result.AccessToken;
}

//App Config File
<add key="ADALServiceURL" value="https://login.microsoftonline.com" />
<add key="ADALRedirectURL" value="http://*****-authentication.cloudapp.net" />
<add key="ARMBillingServiceURL" value="https://management.core.windows.net" />
<add key="TenantDomain" value="********.onmicrosoft.com" />
<add key="SubscriptionID" value="*******-****-****-****-********" />
<add key="ClientId" value="*******-****-****-****-********" />

最佳答案

更新:我还提供了这些方法作为可重用身份验证助手类库。您可以通过此链接找到相同的内容: Azure Authentication - Authenticating any Azure API Request in your Application

方法 1: 要以非交互方式使用密码方法,您需要首先按照以下帖子的“使用密码进行身份验证 - PowerShell”部分进行操作: Authenticating a service principal with ARM

然后使用下面的代码片段来获取 token 。

var authenticationContext = new AuthenticationContext(String.Format("{0}/{1}",
ConfigurationManager.AppSettings["ADALServiceURL"],
ConfigurationManager.AppSettings["TenantDomain"]));
var credential = new ClientCredential(clientId: "11a11111-11a1-111a-a111-1afeda2bca1a", clientSecret: "passwordhere");
var result = authenticationContext.AcquireToken(resource: "https://management.core.windows.net/", clientCredential: credential);

if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}

string token = result.AccessToken;

return token;

或者(方法 2),您也可以使用证书方法。在这种情况下,请使用与上面相同的链接,但请遵循该链接中的“使用证书进行身份验证 - PowerShell”部分。然后使用以下代码片段以非交互方式获取 token :

 var subscriptionId = "1a11aa11-5c9b-4c94-b875-b7b55af5d316";
string tenant = "1a11111a-5713-4b00-a1c3-88da50be3ace";
string clientId = "aa11a111-1050-4892-a2d8-4747441be14d";

var authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenant));

X509Certificate2 cert = null;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
string certName = "MyCert01";

try
{
store.Open(OpenFlags.ReadOnly);
var certCollection = store.Certificates;
var certs = certCollection.Find(X509FindType.FindBySubjectName, certName, false);
//var certs = certCollection.Find(X509FindType.FindBySerialNumber, "E144928868B609D35F72", false);
if (certs == null || certs.Count <= 0)
{
throw new Exception("Certificate " + certName + " not found.");
}
cert = certs[0];
}
finally
{
store.Close();
}

var certCred = new ClientAssertionCertificate(clientId, cert);
var token = authContext.AcquireToken("https://management.core.windows.net/", certCred);
var creds = new TokenCloudCredentials(subscriptionId, token.AccessToken);
//var client = new ResourceManagementClient(creds);
return token.AccessToken;

关于c# - Azure 计费使用 API 返回 401 未经授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34554842/

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