【发布时间】:2019-06-25 04:01:46
【问题描述】:
我正在尝试向托管在 Azure 中并通过 Azure Active Directory 进行身份验证的 API 发送 POST 请求。我正在使用带有React-Adal 的 React 来发送我的请求。我使用 GitHub 存储库和 tutorial 配置了 react-adal 来指导我。
adalConfig.js
import { AuthenticationContext, adalFetch, withAdalLogin, adalGetToken } from 'react-adal';
export const adalConfig = {
tenant: 'ad5842d4-1111-1111-1111-111111111111',
clientId: '1f89aa20-1111-1111-1111-111111111111', //ClientID of the ReactClient application
endpoints: {
demoApi: 'e7926712-1111-1111-1111-111111111111', //ClientID of the DemoApi
microsoftGraphApi: 'https://graph.microsoft.com'
},
postLogoutRedirectUri: window.location.origin,
redirectUri: 'https://localhost:44394/',
cacheLocation: 'sessionStorage'
};
export const authContext = new AuthenticationContext(adalConfig);
export const adalDemoApiFetch = (fetch, url, options) =>
adalFetch(authContext, adalConfig.endpoints.demoApi, fetch, url, options);
export const adalTokenFetch = () =>
adalGetToken(authContext, adalConfig.endpoints.demoApi);
export const withAdalLoginApi = withAdalLogin(authContext, adalConfig.endpoints);
当我将 adalDemoApiFetch 与 GET 请求一起使用时,它可以正常工作并返回 200 和时间表列表。
const url = `https://localhost:44322/api/Schedules/GetAllSchedules`;
const response = await adalDemoApiFetch(axios.get, url);
console.log(response);
const schedules = response.data;
当我使用带有 POST 的相同 adalDemoApiFetch 向列表中添加新计划时,它会返回 401。
const url = `https://localhost:44322/api/Schedules/AddSchedule`;
const azureADID = authContext.getCachedUser();
const token = authContext.acquireToken("e7926712-1111-1111-1111-111111111111");
console.log(token);
const options = {
beginningDateTime: this.state.begDateTime.toJSON(),
endindDateTime: this.state.endDateTime.toJSON(),
userID: this.state.userID,
azureADID: azureADID.profile.oid
};
const response = await adalDemoApiFetch(axios.post, url, options);
console.log(response);
我还尝试复制出令牌并在 Postman 中使用它来进行调用,但它仍然返回 401。当我使用从下面的函数返回的令牌时,它工作得很好。
export const adalTokenFetch = () =>
adalGetToken(authContext, adalConfig.endpoints.demoApi);
我在下面的代码中使用axios调用它,效果很好。
const url = `https://localhost:44322/api/Schedules/AddSchedule`;
const azureADID = authContext.getCachedUser();
const token = await adalTokenFetch();
console.log(token);
const options = {
beginningDateTime: this.state.begDateTime.toJSON(),
endindDateTime: this.state.endDateTime.toJSON(),
userID: this.state.userID,
azureADID: azureADID.profile.oid
};
const response = await axios.post(url,
{
data: options
},
{
headers: {
"Authorization": `Bearer ${token}`
}
}
);
console.log(response);
我做错了什么?为什么它适用于 GET 请求而不适用于 POST 请求?我错过了什么吗?
【问题讨论】:
标签: reactjs asp.net-core azure-active-directory