作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两种方法。根据我已注册的应用程序的 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。这就是您收到身份验证错误的原因。
解决这个问题:
var result = await authenticationContext
.AcquireTokenAsync("https://graph.microsoft.com/", credential);
关于c# - 不记名 token 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58116954/
我是一名优秀的程序员,十分优秀!