我正在开发一个使用 Azure AD 进行身份验证的 Angular2+ 应用。我需要将 token 传递到我的 Web API 层(这可以使用 HttpInterceptor
成功运行),然后在服务器端使用该 token 来调用 Microsoft Graph。
如何将一种 token 转换为另一种 token (最好是在服务器上)?
最佳答案
这正是代表流程的场景。
这是我写的博客文章:https://joonasw.net/view/azure-ad-on-behalf-of-aspnet-core .
That is a fairly long sentence, so let's look at an example scenario where this is used:
- A JavaScript Single Page Application authenticates the user with Azure AD
- The SPA gets an access token for its back-end API and calls the API
- The API then needs to get information about the user's manager from Microsoft Graph API
In this scenario, there are basically two options:
- Use the on-behalf-of grant to acquire an access token that allows the API to call MS Graph as the user
- Use client credentials grant to make the call as the API, with no user context
The first option uses delegated permissions, which mean the data that can be returned is based on what the API and user are allowed to access. It does require the call made to this API was made with a user context.
The second option would instead use application permissions, in which case the app itself would need to have access to this information for any user in the organisation.
You can probably understand why using delegated permissions is usually preferred. It follows the principle of least privilege.
You can find the sample app used in this article at https://github.com/juunas11/azure-ad-on-behalf-of-sample-aspnetcore.
因此,您基本上可以交换从 SPA 获得的 token 以及 API 的凭据,以获得另一个 API 的新访问 token 。这个新 token 也将位于用户上下文中,并将使用委派权限。
下面是一个进行 token 交换的 HTTP 请求示例:
POST https://login.microsoftonline.com/joonasapps.onmicrosoft.com/oauth2/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: login.microsoftonline.com
Content-Length: 1650
Expect: 100-continue
Connection: Keep-Alive
grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&client_id=f3c39179-62f7-45fc-a469-a64fdfce4f91&client_secret=REDACTED&resource=https%3A%2F%2Fgraph.microsoft.com&assertion=eyJ0eLongAccessTokenForThisApi&requested_token_use=on_behalf_of
您可以在这里找到更多信息:https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-on-behalf-of
关于azure-active-directory - 服务器上用于 Graph API 的 ADAL token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48569071/