我需要查询Graph API以获取声明中的用户名。 我已经根据网上发现的东西实施了一些东西,但是我从Graph API不断收到403 Forbidden。 有人可以帮我吗?
这是我的代码:
var clientId = "clientId";
var clientSecret = "clienSecret";
var tenant = "tenantName";
var userObjectId = claimsPrincipal.Claims.Where(i => i.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier").FirstOrDefault().Value;
var aadGraphVersion = "api-version=1.6";
var query = "/users/" + userObjectId;
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenant);
// The ClientCredential is where you pass in your client_id and client_secret, which are
// provided to Azure AD in order to receive an access_token using the app's identity.
ClientCredential credential = new ClientCredential(clientId, clientSecret);
// First, use ADAL to acquire a token using the app's identity (the credential)
// The first parameter is the resource we want an access_token for; in this case, the Graph API.
AuthenticationResult result = await authContext.AcquireTokenAsync("https://graph.windows.net", credential);
// For B2C user management, be sure to use the Azure AD Graph API for now.
HttpClient http = new HttpClient();
//var url = "https://graph.windows.net/" + tenant + "/users/" + userObjectId + "/?api-version=1.6";
//var url = graphResource + "tenant" + "/users/" + userObjectId + "/?api-version=1.6";
string url = "https://graph.windows.net/" + tenant + "/users/" + userObjectId + "?" + aadGraphVersion;
//url += "&" + query;
// Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await http.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
string error = await response.Content.ReadAsStringAsync();
object formatted = JsonConvert.DeserializeObject(error);
throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
}
我认为URL
设置不正确有问题。令牌是正确的,我对凭据没有问题。
答案 0 :(得分:0)
我确实认为这是URL的问题。您已经为用户提供了对已注册应用程序的读取权限,因此出现此错误。请确保-
如果希望提供应用程序来创建/更新/删除用户,则可能需要选择“读取和写入目录数据”之类的其他选项。