我正在编写一个网络 API。它所做的其中一件事是使用 Team Foundation Core DLL 实现 Azure DevOps。由于我们得到 Azure AD(Azure Active Directory)的支持,我想我可以让我的应用程序针对 Azure AD 进行身份验证,并将该 token /授权用于 Azure DevOps。这不是它要进行身份验证的唯一服务。我可以这样做吗?还有什么其他方法可以实现这个目标?我不想在每次访问独特服务时提示用户针对 Azure AD 进行授权,尤其是因为它们都由 Azure AD 提供支持。
最佳答案
是的,你可以做到这一点。
注意:我假设您的 API 受 Azure AD 保护,并且为了调用您的 API,用户需要使用 Azure AD 登录到您的 API 客户端。
假设您希望您的 API 不仅向 Azure DevOps 发出请求,而且向 Microsoft Graph 发出请求(以 Azure AD 保护的另一个 API 为例——这当然可以是任何其他 API,包括第二个 API您自己的),并且您希望这些请求代表登录用户。也就是说,代表 API 收到的访问 token 中标识的用户。
您可以执行以下操作(下图):
- 用户使用 Azure AD 登录客户端应用程序,客户端应用程序请求 API 和访问 token 。
- 客户端应用程序在发出任何 API 请求时(例如在 Authorization header 中)向您的 API 提供此访问 token ,并且您的 API 会执行所有必要的验证。
- 您的 API 获取它收到的访问 token ,并将其呈现给 Azure AD,从提供的访问 token “代表”登录用户请求一个新访问 token ,但对于不同的资源:Azure DevOps。假设所有正确的权限和同意都已到位,Azure AD 会使用 Azure DevOps 的访问 token 响应 API。
- API 在向 Azure DevOps 发出请求时提供此访问 token 。
- 您的 API 还想调用 Microsoft Graph(例如,获取有关用户的更多详细信息,或发送电子邮件等),因此 API 再次转到 Azure AD,显示它在 (2) 中收到的访问 token ,向 Microsoft Graph 请求 token 。如果同意和权限得到验证,Azure AD 将符合要求。
- 您的 API 在向 Microsoft Graph 发出请求时使用这第三个访问 token 。
+--------+ +-----------+ +-----------------+
(User)+---> +-(2)--> +-(4)---> |
| Client | | Your API <-------+ Azure DevOps |
| <------+ | | |
+----^---+ | +-(6)+ +-----------------+
| | | <--+ |
| | +---^----^--+ | | +-----------------+
(1) (3) (5) | +--> |
| | || || +----+ Microsoft Graph |
| | +--v----v--+ | (or other API) |
| +--------> | | |
| | Azure AD | +-----------------+
+----------+ |
+----------+
Azure AD 文档中描述了详细的 token 流(适用于 v1 endpoint 和 v2 endpoint)。
当然,这里所有的复杂性,以及 token 缓存和刷新,都应该由简单的库处理,例如 ADAL 或 MSAL,它们都有用于代表流程的 wiki 页面(with ADAL, with MSAL)。下面是 ADAL 外观的总结示例(取自 To
// Use ADAL to get a token On Behalf Of the current user. To do this we will need:
// The Resource ID of the service we want to call.
// The current user's access token, from the current request's authorization header.
// The credentials of this application.
// The username of the user calling the API
//
string resourceId = "499b84ac-1321-427f-aa17-267ca6975798"; // this is the Azure DevOps app ID
string userName = "...";// get from incoming token
string userAccessToken = "..." // from incoming Authorization header;
UserAssertion userAssertion = new UserAssertion(userAccessToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);
ClientCredential clientCred = new ClientCredential(clientId, appKey);
AuthenticationContext authContext = new AuthenticationContext(authority, tokenCache);
// Now make the on-behalf-of request
result = await authContext.AcquireTokenAsync(resourceId, clientCred, userAssertion);
accessToken = result.AccessToken; // <-- this is a token for Azure DevOps!
关于azure-devops - 使用 Azure AD token 通过 Azure DevOps 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52896114/