简体   繁体   English

Azure B2C无法访问图形API

[英]Azure B2C cannot access graph api

I got an access token to fetch the graph client using the following code: 我使用以下代码获取访问令牌以获取图形客户端:

    string graphResourceID = "https://graph.windows.net";      
    string tenantID = ConfigurationManager.AppSettings["ida:Domain"];
    string aadInstance = "https://login.microsoftonline.com/" + tenantID + 
    "/oauth2/v2.0/token";

Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, appKey);
AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance);
authenticationContext.TokenCache.Clear();

var authResult = await authenticationContext.AcquireTokenAsync(graphResourceID,clientcred);

And then tried to use the token to fetch the signed in User's info via the AD graph api: 然后尝试使用令牌通过AD图形API获取已登录的用户信息:

Uri servicePointUri = new Uri(graphResourceID);
Uri serviceRoot = new Uri(servicePointUri, tenantID);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,async () => await GetTokenForApplication());    
var result = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync();
IUser user = result.CurrentPage.ToList().First();

return View(user);

However, this returns the following error: 但是,这将返回以下错误:

"error": {
"code": "Authorization_IdentityNotFound",
"message": "The identity of the calling application could not be established.",
"innerError": {
"request-id": "2bdae8ff-d935-4e01-80a1-78cbc8acf4de",
"date": "2017-08-09T18:07:40"

I made sure that mu B2C application has the "Read and Write Directory Data" permission for Windows Active Directory : 我确保mu B2C应用程序对Windows Active Directory具有“读取和写入目录数据”权限:

在此处输入图片说明

Can anyone please help? 谁能帮忙吗? Been stuck on this for a while. 坚持了一段时间。 TIA TIA

Edit 编辑

I also tried using Microsoft.Graph but end up getting the same error. 我也尝试使用Microsoft.Graph,但最终遇到相同的错误。 Plus for B2C users I think it's best if we stick to Azure Ad Graph api for now: https://dev.office.com/blogs/microsoft-graph-or-azure-ad-graph 对于B2C用户,我认为最好还是暂时使用Azure广告图api: https : //dev.office.com/blogs/microsoft-graph-or-azure-ad-graph

It seems that you use the Azure AD library to operate Graph API. 似乎您使用Azure AD库来操作Graph API。 I recommand that you could use Microsoft.Graph to do that. 我建议您可以使用Microsoft.Graph来做到这一点。 Please also set the permission with Microsoft Graph. 请同时使用Microsoft Graph设置权限。

Note : don't forget to click [ Grant Permissions ] button. 注意 :不要忘记单击[ 授予权限 ]按钮。

在此处输入图片说明

The following is the demo code. 以下是演示代码。

string graphResourceId = "https://graph.microsoft.com/";
string authority = "https://login.microsoftonline.com/{0}";
string tenantId = "tenantId";
string clientId = "client Id";
string secretKey = "secret key"
var accessToken = authContext.AcquireTokenAsync(graphResourceId, new ClientCredential(clientId,secret)).Result.AccessToken;
var graphserviceClient = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    requestMessage =>
                    {
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                        return Task.FromResult(0);
                    }));
var user = graphserviceClient.Users.Request().GetAsync().Result.FirstOrDefault();

Test Result: 测试结果:

在此处输入图片说明

Update: 更新:

I also test with Azure AD graph API with Azure B2c, it also works correctly on my side. 我还使用Azure B2c对Azure AD图形API进行了测试,它也可以正常运行。 I also assign the [Read and write directory data] and click [Grant permissions] without other permission setting. 我还分配了[读取和写入目录数据],然后单击没有其他权限设置的[授予权限]。

The following is the demo code I used for test. 以下是我用于测试的演示代码。

 string graphResourceID = "https://graph.windows.net";
 string tenantID = "tenant Id";
 Uri servicePointUri = new Uri(graphResourceID);
 Uri serviceRoot = new Uri(servicePointUri, tenantID);
 ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await GetAppTokenAsync());
 var result =  activeDirectoryClient.Users.ExecuteAsync().Result;
 IUser user = result.CurrentPage.ToList().First();



 private static async Task<string> GetAppTokenAsync()
 {
        string graphResourceID = "https://graph.windows.net";
        string tenantID = "tenant id ";
        //please remove v2 from the link
        string aadInstance = "https://login.microsoftonline.com/" + tenantID +"/oauth2/token";
        var clientId = "client Id";
        var appKey = "secret key";
        // Instantiate an AuthenticationContext for my directory (see authString above).
        AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance, false);
        // Create a ClientCredential that will be used for authentication.
        // This is where the Client ID and Key/Secret from the Azure Management Portal is used.
        ClientCredential clientCred = new ClientCredential(clientId, appKey);
        // Acquire an access token from Azure AD to access the Azure AD Graph (the resource)
        // using the Client ID and Key/Secret as credentials.
        AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(graphResourceID, clientCred); 
        // Return the access token.
        return authenticationResult.AccessToken;
   }

Test Result: 测试结果:

在此处输入图片说明

If it still doesn't work for you. 如果仍然不适合您。 I suggest you create a new Azure AD application and try it again. 建议您创建一个新的Azure AD应用程序,然后重试。

Packages.config: Packages.config:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Azure.ActiveDirectory.GraphClient" version="2.1.1" targetFramework="net471" />
  <package id="Microsoft.Data.Edm" version="5.6.4" targetFramework="net471" />
  <package id="Microsoft.Data.OData" version="5.6.4" targetFramework="net471" />
  <package id="Microsoft.Data.Services.Client" version="5.6.4" targetFramework="net471" />
  <package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="3.19.8" targetFramework="net471" />
  <package id="System.Spatial" version="5.6.4" targetFramework="net471" />
</packages>

Thanks guys it seems I was using the tenant ID of the original directory I used to create my B2C directory. 谢谢大家,看来我使用的是我用来创建B2C目录的原始目录的租户ID。 Hence the code could not find my application. 因此,代码找不到我的应用程序。 I have to use the tenant ID/domain name of my Azure B2C directory where the B2C app is registered by clicking on switch directory in the upper right corner of the portal. 我必须通过单击门户右上角的switch目录,使用我的Azure B2C目录的租户ID /域名来注册B2C应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM