gpt4 book ai didi

c# - 如何为我的 Azure 应用程序创建应用程序 token ?

转载 作者:行者123 更新时间:2023-12-03 00:17:37 25 4
gpt4 key购买 nike

因此,我尝试从我的 Azure 应用程序中存在的“OAuth 2.0 token 端点 (v2)”端点获取 token 。就是这样。

[HttpGet("GetApplicationToken")]
public async Task<ActionResult> GetApplicationToken()
{
HttpClient client = new HttpClient();
var url = "https://login.microsoftonline.com/680ea9b1-xxxx-xxxx-xxxx-xxxxxxxxxxxx/oauth2/v2.0/token";

var parameters = new Dictionary<string, string>
{
{"client_id", "41d391ef-xxxx-xxxx-xxxx-xxxxxxxxxxxx" },
{"scope", "api://41d391ef-xxxx-xxxx-xxxx-xxxxxxxxxxxx/access_as_user" },
{"client_secret", "PXa8Q~xx" },
{"grant_type", "client_credentials" }
};
var encodedContent = new FormUrlEncodedContent(parameters);

var response = await client.PostAsync(url, encodedContent);

if (response.IsSuccessStatusCode)
{
var responseStr = await response.Content.ReadAsStringAsync();
return Ok(JsonConvert.DeserializeObject<TokenResponse>(responseStr));
}

return StatusCode(500);

我得到的输出是:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.6.1","title":"An error occurred while processing your request.","status":500,"traceId":"00-d0da4fd71ec21cb0f8b364e3853bda37-ed1dcd82609eef73-00"}

我希望它返回一个我的 api 可以使用的应用程序 token ,但我不知道问题可能是什么。谢谢!

最佳答案

使用客户端凭据流程时,范围参数应为“api://41d391ef-xxxx-xxxx-xxxx-xxxxxxxxxxxx/.default”。这是因为您只能在应用注册中使用静态定义的权限,这与涉及用户的身份验证流程不同,身份验证流程可以动态使用范围。

文档:https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow#first-case-access-token-request-with-a-shared-secret .

引用有关范围参数的文档:

The value passed for the scope parameter in this request should be the resource identifier (application ID URI) of the resource you want, affixed with the .default suffix.

(除了应用程序 ID URI 之外,它也可以是客户端/应用程序 ID)

此外,无论状态码是否成功,都最好读取响应内容,这样您就可以检查返回的错误。此外,使用 MSAL 会更容易为此,无需手动调用 API。

关于c# - 如何为我的 Azure 应用程序创建应用程序 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75885711/

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