设置GraphApi B2C登录的URL

时间:2018-10-09 09:34:30

标签: microsoft-graph azure-ad-b2c

我需要查询Graph API以获取声明中的用户名。 我已经根据网上发现的东西实施了一些东西,但是我从Graph API不断收到403 Forbidden。 有人可以帮我吗?

enter image description here

这是我的代码:

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

1 个答案:

答案 0 :(得分:0)

我确实认为这是URL的问题。您已经为用户提供了对已注册应用程序的读取权限,因此出现此错误。请确保-

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

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