azure - 代表当前登录到单独 Web 客户端的用户从 API 访问 MS Graph

标签 azure azure-active-directory asp.net-core-2.0 microsoft-graph-api azure-authentication

我正在开发一个 API(ASP.NET Core),可以通过单独托管的 Web 客户端(React)访问,两者都作为应用程序服务托管在 azure 上。 客户端应用程序必须具有基于azure Ad的身份验证(单租户,最好由基于aad的azure身份验证保护)。 当用户登录客户端时,API 必须能够代表用户访问 MS Graph。显然,这两个资源都必须受到保护,我已经尝试在两个应用程序服务上使用基于 AAD 的 azure auth,但在这种方法中,我无法使用从 API 端的 auth 到 ADD 获得的 token 来获取 MsGraph 的 token 。

问题是,如何避免使用来自客户端的azure aad auth token 将 token 传递给MsGraph,并仅根据来自aad auth的 token 获取msGraph的 token ,同时只有一个位置供用户登录并确保两个应用程序服务的安全?

我在 Api 端使用 MsGraph 的 nugget 来与 MsGraph 交互。我还没有找到任何涉及此特定案例的示例。

最佳答案

场景:您的应用程序的 Web API(受 Azure AD 保护)从客户端应用程序 (React) 接收身份验证 token ,并且需要代表签名的下游 Web API (Microsoft Graph) 调用在用户中。

Microsoft Docs 上的概念文档:您的方案与 OAuth 2.0 代表流程完全匹配,如 Azure AD 的 Microsoft Docs 中所述 Service-to-service calls that use delegated user identity in the On-Behalf-Of flow

代码示例:

重要代码

这就是您如何使用已传入的 token 来获取新 token ,并使用该 token 代表用户从 Web API 调用 Microsoft Graph API。

准备用户断言:

ClientCredential clientCred = new ClientCredential(clientId, appKey);
var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;
string userName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
string userAccessToken = bootstrapContext.Token;
UserAssertion userAssertion = new UserAssertion(userAccessToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);

获取 Microsoft Graph 的 token :

 result = await authContext.AcquireTokenAsync(graphResourceId, clientCred, userAssertion);

关于azure - 代表当前登录到单独 Web 客户端的用户从 API 访问 MS Graph,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53732255/

相关文章:

asp.net-mvc - 来自 azure Webjob 的 Identity 2.0/Owin/ApplicationUser

azure - 尝试使用 Azure AD 登录时出现错误 AADSTS65001

c# - Configuration.GetSection() 可以轻松获取原始字符串值,但不能获取复杂值

azure - 我应该如何使用 .net core c# 从死信中读取更多数量的消息?

列表中缺少 Azure Web 作业

Azure Pipelines 每个拉取请求触发 2 个作业

azure - 为 Azure SQL DB 创建 AD 用户时出现语法错误

Azure Devops - 生产部署的服务主体手动(或)服务主体自动?

c# - 调用 AddUserAsync .NET Core 2.0 时出现 PlatformNotSupported 异常

reactjs - 在 SSR 期间获取主机名