【发布时间】:2020-09-14 13:29:50
【问题描述】:
我有一个 C# MVC Web 应用程序,我试图通过它使用 Microsoft Graph API 读取用户组。但是,当我尝试通过使用 HttpClient 的代码执行此操作时,我收到“403 Forbidden”错误。 我拥有所有必需的权限,但仍然收到错误,无法获得错误的原因或任何解决方案。我什至尝试用谷歌搜索,但找不到任何东西。
如果有人可以帮忙。
try
{
using (var httpClient = new HttpClient(HttpClientHelper.GetWinHttpHandler()))
{
var json = @"{ 'securityEnabledOnly': true }";
var stringContent = new StringContent(json);
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + graphapitoken);
httpClient.BaseAddress = new Uri("https://graph.microsoft.com/");
var response = Task.Run(() => httpClient.PostAsync($"v1.0/users/" + UsermailId + "/getMemberGroups", new StringContent(json, Encoding.UTF8, "application/json")));
response.Wait();
if (response.Result.IsSuccessStatusCode)
{
string strResponse = await response.Result.Content.ReadAsStringAsync();
object dec = JsonConvert.DeserializeObject(strResponse);
JObject obj = JObject.Parse(dec.ToString());
List<JToken> obj1 = obj["value"].ToList();
listAssociatedGroups = obj1.Values<string>().ToList();
}
}
}
获取令牌
public class Token
{
public static string GetToken()
{
return GraphToken(ConfigurationManager.AppSettings["ida:Tenant"],ConfigurationManager.AppSettings["ida:ClientId"], ConfigurationManager.AppSettings["ida:ClientSecret"]);
}
private static string GraphToken(string tenantId, string clientId, string clientSecret)
{
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenantId);
ClientCredential credential = new ClientCredential(clientId, clientSecret);
AuthenticationResult result = authContext.AcquireTokenAsync("https://graph.microsoft.com", credential).GetAwaiter().GetResult();
return result.AccessToken;
}
public static string TokenAsync(string tenantId, string clientId, string clientSecret, string resourceURI)
{
try
{
var authenticationContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}");
ClientCredential credential = new ClientCredential(clientId, clientSecret);
var authenticationResult = authenticationContext.AcquireTokenAsync(resourceURI, credential).GetAwaiter().GetResult();
return authenticationResult.AccessToken;
}
catch (Exception ex)
{
throw new Exception("Failed to retrive AAD token");
}
}
}
我拥有的 API 权限
【问题讨论】:
-
转到 Azure 门户>应用注册>API 权限并提供屏幕截图。
-
对于 /users 端点,它通常不需要用户登录,因此您需要将 应用程序权限 授予您的应用程序和授予管理员同意。您可以使用客户端凭证流来请求令牌。 docs.microsoft.com/en-us/azure/active-directory/develop/…
-
@CarlZhao 我的应用程序在 Microsoft 生产租户中,并且确实获得了 Microsoft 租户中 API 权限的管理员同意。而且我还获得了正确的访问令牌,并且我也从 Graph Explorer 验证了这一点。我在调用“PostAsync”方法或 HTTPCLIENT 的任何其他方法时收到“Forbidden”错误。
-
你需要应用程序权限,而不是委托权限,因为你不是以用户身份登录的,所以这些委托权限对你没有用,所以请向您的应用授予应用权限
-
正如我在评论中所说,对于
/users端点,它通常不需要用户登录。
标签: c# microsoft-graph-api dotnet-httpclient