我正在开发一个 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
代码示例:
- Service to service calls on behalf of the user (来自 GitHub 上的 Azure-Samples)
- Calling a downstream web API from a web API on behalf of user (来自 GitHub 上的 Azure-Samples)
- Using Azure AD On-Behalf-Of flow in an ASP.NET Core 2.0 API (并非直接来自 Microsoft 样本,而是来自 MVP Joonas W 的博客)
重要代码
这就是您如何使用已传入的 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/