我有一个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权限
答案 0 :(得分:0)
只是在黑暗中刺伤: 其中某些权限需要管理员同意。 您的应用程序是否具有这些权限的管理员同意?
答案 1 :(得分:0)
首先,您可以直接使用Graph Explorer测试此API。
POST https://graph.microsoft.com/v1.0/me/getMemberGroups
{
"securityEnabledOnly": true
}
我不确定您用来获取代码中的访问令牌的流程类型。如果使用client credentials flow,则需要添加应用程序权限之一。委派的权限可用于其他流程。