gpt4 book ai didi

c# - 如何从 azure OAuth 2.0 token (v2) 端点获取/生成访问 token ?

转载 作者:行者123 更新时间:2023-12-02 22:55:57 25 4
gpt4 key购买 nike

我想从给定的 URL 获取访问 token :

https://login.microsoftonline.com/{AzureTenantId}/oauth2/v2.0/token

我正在传递以下参数,如 Microsoft 文档中所述:client_id范围client_secretgrant_type

当我点击此 URL 时,我收到“400 Bad Request”响应。

当我从 Postman 尝试相同的操作时,它成功并为我提供了一个访问 token :

success postman request

但不是来 self 的代码:

public async Task<string> GetAuthorizationToken(string clientId, string ServicePrincipalPassword, string AzureTenantId) {
var result = "";
var requestURL = "https://login.microsoftonline.com/{AzureTenantId}/oauth2/v2.0/token";
var _httpClient = new HttpClient();

var model = new {
client_id = clientId,
scope = "{clentID}/.default",
client_secret = ServicePrincipalPassword,
grant_type = "client_credentials"
};

HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(model), System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");

var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(requestURL)) {
Content = httpContent
};

using (var response = await _httpClient.SendAsync(httpRequestMessage)) {
if (response.IsSuccessStatusCode) {
var responseStream = await response.Content.ReadAsStringAsync();
return result;
} else {
return result;
}
}

最佳答案

您的http请求格式不正确,请尝试:

var _httpClient = new HttpClient();

var content = new FormUrlEncodedContent(new Dictionary<string, string> {
{ "client_id", "ClientID" },
{ "client_secret", "YourSecret" },
{ "grant_type", "client_credentials" },
{ "scope", "https://graph.microsoft.com/.default" },
});

var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(requestURL))
{
Content = content
};

using (var response = await _httpClient.SendAsync(httpRequestMessage))
{
if (response.IsSuccessStatusCode)
{
var responseStream = await response.Content.ReadAsStringAsync();
return result;
}
else
{
return result;
}
}

关于c# - 如何从 azure OAuth 2.0 token (v2) 端点获取/生成访问 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56179837/

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