首页 > 解决方案 > 设置 GraphApi B2C 登录 url

问题描述

我需要查询 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设置不正确有问题。令牌是正确的,我对凭据没问题。

标签: microsoft-graph-apiazure-ad-b2c

解决方案


我确实认为这是URL的问题。由于您为注册的应用程序提供了用户读取权限,因此您收到此错误。请确保 -

  1. 您转到租户上的应用程序注册菜单
  2. 选择“必需权限”菜单并单击Windows Azure Active Directory
  3. 在“启用访问”菜单中,选择“应用程序权限”部分下的“读取目录数据”权限,然后单击保存。
  4. 保存在“必需权限”菜单上后,单击“授予权限”按钮以提供同意。

如果您希望提供您的应用程序来创建/更新/删除用户,您可能需要选择其他选项,例如“读取和写入目录数据”。


推荐阅读