多租户应用程序中的B2B访问

本文关键字:B2B 访问 应用程序 | 更新日期: 2023-09-27 18:18:05

我已经成功地设置了一个多租户应用程序。目前,我能够对用户进行身份验证,并使用令牌访问其他资源。(Microsoft Graph &;微软广告图表)

现在我想让B2B工作。电流:-用户登录authorizationcoderreceived获取获取令牌(通过$commonAuthority端点)-当为广告图请求令牌时,我使用$tenantAuthority

当$tenantAuthority与创建帐户的租户权限相同时,此操作可以完美地工作。

但是,如果我用另一个用户(从另一个租户,给予信任的实际租户)登录并使用$tenantAuthority =可信权限,那么我总是出现以下错误:刷新令牌失败:AADSTS65001:用户或管理员未同意使用ID

的应用程序

如果我将$tenantAuthority更改为创建用户的"源"租户权限,则一切正常。

任何帮助都将是非常感激的。

更新:代码示例

应用程序有两个租户(tenantA和tenantB),我将使用tenantB的用户,tenantA给予该用户信任。

AuthorizationCodeReceived = async context =>
                    {
                        TenantContext.TenantId = "someguid";
                        var tenantId =
                            TenantContext.TenantId;
                        // get token cache via func, because the userid is only known at runtime
                        var getTokenCache = container.Resolve<Func<string, TokenCache>>();
                        var userId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.ObjectIdentifier).Value;
                        var tokenCache = getTokenCache(userId);
                        var authenticationContext = new AuthenticationContext($"{configuration.Authority}",
                            tokenCache);
                        await authenticationContext.AcquireTokenByAuthorizationCodeAsync(
                            context.Code,
                            new Uri(context.Request.Uri.GetLeftPart(UriPartial.Authority)),
                            new ClientCredential(configuration.ClientId, configuration.ClientSecret),
                            configuration.GraphResourceId);
                    }

这段代码工作得很完美。在两个租户中使用一个用户登录非常有效。

但是当我需要图形服务客户端或ActiveDirectoryClient时,我需要获得访问令牌,以便能够为某个租户寻址api。我像这样检索访问令牌:

public IGraphServiceClient CreateGraphServiceClient()
    {
        var client = new GraphServiceClient(
            new DelegateAuthenticationProvider(
                async requestMessage =>
                {
                    Logger.Debug("Retrieving authentication token to use in Microsoft Graph.");
                    string token;
                    var currentUserHomeTenantId = TenantContext.TenantId;
                    var currentUserObjectId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.ObjectIdentifier).Value;
                    var authenticationContext =
                        new AuthenticationContext($"{_configuration.TenantAuthorityPrefix}{currentUserHomeTenantId}",
                            _tokenCacheFactoryMethod(currentUserObjectId));
                    var clientCredential = new ClientCredential(_configuration.ClientId, _configuration.ClientSecret);
                    try
                    {
                        token = await GetTokenSilently(authenticationContext, _configuration.GraphResourceId, currentUserObjectId);
                    }
                    catch (AdalSilentTokenAcquisitionException e)
                    {
                        Logger.Error("Failed to retrieve authentication token silently, trying to refresh the token.", e);
                        var result = await authenticationContext.AcquireTokenAsync(_configuration.GraphResourceId, clientCredential);
                        token = result.AccessToken;
                    }
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue(AuthenticationHeaderKeys.Bearer, token);
                }));
        return client;
    }

    public IActiveDirectoryClient CreateAdClient()
    {
        var currentUserHomeTenantId = TenantContext.TenantId;
        var currentUserObjectId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.ObjectIdentifier).Value;
        var graphServiceUrl = $"{_configuration.AdGraphResourceId}/{currentUserHomeTenantId}";
        var tokenCache = _tokenCacheFactoryMethod(currentUserObjectId);
        var client = new ActiveDirectoryClient(new Uri(graphServiceUrl),
            () => GetTokenSilently(
                new AuthenticationContext(
                    $"{_configuration.TenantAuthorityPrefix}{ClaimsPrincipal.Current.FindFirst(ClaimTypes.TenantId).Value}", tokenCache
                ),
                _configuration.AdGraphResourceId, currentUserObjectId
            ));
        return client;
    }

当我用两个客户端SDK中的一个做请求时,我得到了以下错误:刷新令牌失败:AADSTS65001:用户或管理员不同意使用具有ID的应用程序。

多租户应用程序中的B2B访问

在检索令牌时更改catch方法达到了目的:

if(e.ErrorCode == "failed_to_acquire_token_silently")
{
    HttpContext.Current.Response.Redirect(authenticationContext.GetAuthorizationRequestUrlAsync(resourceId, _configuration.ClientId, new Uri(currentUrl),
                        new UserIdentifier(currentUserId, UserIdentifierType.UniqueId), string.Empty);
}

我没有看到您提到这一点:在B2B协作中,您必须首先从其他租户邀请用户。步骤如下:

  • 通过上传一个以逗号分隔的值的CSV文件来邀请和授权一组外部用户
  • 邀请将发送给外部用户。
  • 被邀请的用户将登录到Microsoft的现有工作帐户(在Azure AD中管理),或在Azure AD中获得新的工作帐户。
  • 登录后,用户将被重定向到与他们共享的应用程序

这在我的情况下很好。

关于我发现的一些问题:

活动目录资源末尾的"/"-尝试删除它,因为这可能会导致问题。下面你会发现一些代码来获得认证头:

string aadTenant = WebServiceClientConfiguration.Settings.ActiveDirectoryTenant;
string clientAppId = WebServiceClientConfiguration.Settings.ClientAppId;
string clientKey = WebServiceClientConfiguration.Settings.ClientKey;
string aadResource = WebServiceClientConfiguration.Settings.ActiveDirectoryResource;
AuthenticationContext authenticationContext = new AuthenticationContext(aadTenant);
ClientCredential clientCredential = new ClientCredential(clientAppId, clientKey);
UserPasswordCredential upc = new UserPasswordCredential(WebServiceClientConfiguration.Settings.UserName, WebServiceClientConfiguration.Settings.Password);
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(aadResource, clientAppId, upc);
return authenticationResult.CreateAuthorizationHeader();

默认情况下,Azure AD中配置的应用程序不允许使用OAuth2隐式授权。你需要显式地选择 -更多细节可以在这里找到:Azure AD OAuth2隐式授予