【发布时间】:2020-03-30 21:59:27
【问题描述】:
我有一个在 Azure Active Directory 中注册的 React 应用程序。在 API 权限部分,我添加了访问我尝试访问的 API 的权限。
当用户进入应用程序时,我正在使用 react-adal 包来处理登录和访问令牌的存储。我的理解是,此时创建了 API 的访问令牌,adalFetch 在调用 API 期间处理后勤工作。
来自 API 的响应是一个错误对象(我替换了实际的 id;是的,它们完全匹配并且在 AAD 中是正确的):
{
message: "AADSTS500011: The resource principal named https://<domain>.onmicrosoft.com/APP_ID/access_as_user was not found in the tenant named TENANT. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant."
msg: "invalid_resource"
}
我已经到处搜索以找到解决此问题的方法。 API 上有文档,但没有指定资源或各种端点之外的任何内容,即http://thing-api.azurewebsites.net/api/endpointGoesHere
API 页面声明:
要使用 API,应用需要使用 AzureAD (AAD) 实现现代身份验证 (OIDC),然后从 AAD 请求 API 的令牌。
Azure 中的应用 ID 为 https://domain.onmicrosoft.com/APP_ID,需要“access_as_user”范围。
adalConfig.js
import { AuthenticationContext, adalFetch, withAdalLogin } from 'react-adal';
export const adalConfig = {
clientId: CLIENT_ID,
tenant: TENANT,
endpoints: {
thingApi: 'https://<domain>.onmicrosoft.com/APP_ID/access_as_user',
graphApi: 'https://graph.microsoft.com',
},
cacheLocation: 'localStorage',
};
export const authContext = new AuthenticationContext(adalConfig);
export const adalApiFetch = (fetch, url, options) =>
adalFetch(authContext, adalConfig.endpoints.thingApi, fetch, url, options);
export const adalGraphFetch = (fetch, url, options) =>
adalFetch(authContext, adalConfig.endpoints.graphApi, fetch, url, options);
API 调用的函数。在 componentDidMount 中执行。
TrainLanding.jsx
//Returns error
fetchData = () => {
adalApiFetch(fetch, 'http://thing-api.azurewebsites.net/api/EventGet', {})
.then((response) => {
response.json()
.then((responseJson) => {
this.setState({ apiResponse: JSON.stringify(responseJson, null, 2) }, () => {
console.log(this.state.apiResponse)
})
});
})
.catch((error) => {
console.error(error);
})
}
//works perfectly fine
fetchGraph = () => {
adalGraphFetch(fetch, 'https://graph.microsoft.com/v1.0/me', {})
.then((response) => {
response.json()
.then((responseJson) => {
this.setState({ apiResponse: JSON.stringify(responseJson, null, 2) }, () => {
console.log(this.state.apiResponse)
})
});
})
.catch((error) => {
console.error(error);
})
}
我以完全相同的方式设置了一个图形 API 调用来测试该方法,它工作得非常好。所以我知道 adal 设置正确,我只是不明白错误和哪里出错了。我的谷歌搜索没有产生任何有用的结果。
【问题讨论】:
-
我认为您将 v1 (adal) 与 v2 (MSAL) 混合在一起。 ADAL 不使用范围,它仅使用资源标识符。因此,在您的情况下,API 客户端 ID 或应用 ID URI。
-
好的,谢谢你的提示。我不知道 ADAL 无法使用作用域。我会考虑使用我找到的 react-aad-msal 包!
-
@robertb.webdev 如果您的问题已经解决,您可以添加您的解决方案作为答案。如果您对此有任何其他疑虑,请更新您的问题。
-
我收到此错误{消息:“AADSTS500011:资源主体名为 https://…959-c767cc4c040b ↵时间戳:2019-06-10 12:18:02Z”,消息:“invalid_resource”}
标签: reactjs rest azure-active-directory adal