gpt4 book ai didi

c# - 不记名 token 无效

转载 作者:行者123 更新时间:2023-12-03 04:08:43 26 4
gpt4 key购买 nike

我有两种方法。根据我已注册的应用程序的 Azure ClientID 和 Azure key 获取并返回访问 token 。然后,第二个函数调用 Azure 函数,但该函数返回错误:

[9/26/2019 12:18:49 PM] Creating a new Team.

[9/26/2019 12:19:00 PM] Executed 'AddTeam' (Failed, Id=aaecc7fa-e3bd-40e7-8be9-a 8a173cc166b)

[9/26/2019 12:19:00 PM] System.Private.CoreLib: Exception while executing functi on: AddTeam. System.Net.Http: The format of value 'Bearer ' is invalid.

非常感谢任何帮助,因为它让我发疯!

public static async Task<string> GetAccessToken()
{
string clientId = "clientIDFromAzure";
string clientKey = "secretKeyFromAzure";

string authContextURL = "https://login.microsoftonline.com/tennantID";
var authenticationContext = new AuthenticationContext(authContextURL);
var credential = new ClientCredential(clientId, clientKey);
var result = await authenticationContext
.AcquireTokenAsync("https://management.azure.com/", credential);
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the token");
}
string token = result.AccessToken;
return token;
}

public static async Task<string> CallGraph(HttpMethod method, string uri, string body)
{

HttpClient httpClient = new HttpClient();
string graphEndpoint = "https://graph.microsoft.com/";

var request = new HttpRequestMessage(method, graphEndpoint + uri);
request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

string accessToken = await TokenHelper.GetAccessToken();

request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer ", accessToken);

if (method != HttpMethod.Get)
request.Content = new StringContent(body, Encoding.UTF8, "applciation/json");
HttpResponseMessage response = await httpClient.SendAsync(request);
string responseBody = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
throw new Exception(responseBody);
return responseBody;
}

最佳答案

GetAccessToken 方法中,您尝试获取 Azure 管理 API 的访问 token 。

var result = await authenticationContext
.AcquireTokenAsync("https://management.azure.com/", credential);

但是,您实际上使用该 token 来调用 Microsoft Graph API。这就是您收到身份验证错误的原因。

解决这个问题:

  1. 您需要在 Azure AD 中注册的应用中添加必要的 Graph API 权限,然后授予这些权限的同意。

enter image description here

  • 修改您的代码以获取 Microsoft Graph API 的 token 。
  • var result = await authenticationContext
    .AcquireTokenAsync("https://graph.microsoft.com/", credential);

    关于c# - 不记名 token 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58116954/

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