此处的键在中
adalApiFetch定义
adalConfig.js。如您所见,这是一个简单的包装
adalFetch。此方法(在中定义
react-adal)接收ADAL实例(
authContext),资源标识符(
resourceGuiId),方法(
fetch),URL(
url)和对象(
options)。该方法执行以下操作:
- 使用ADAL实例(
authContext
)获取由标识的资源的访问令牌resourceGuiId
。 - 将此访问令牌添加到对象的
headers
字段中options
(如果未提供,则创建一个)。 - 调用传入的给定“获取”方法,
url
并将options
对象作为参数。
该
adalApiFetch方法(您已在中定义
adalConfig.js)仅
adalFetch使用中标识的资源进行调用
adalConfig.endpoints.api。
好的,那么您如何使用所有这些来发出REST请求,并在React应用程序中使用响应?让我们举个例子。在以下示例中,我们将使用Microsoft Graph
API作为受Azure AD保护的REST API。我们将通过友好的标识符URI(“
https://graph.microsoft.com
”)来识别它,但是请记住,那也可以是Guid应用程序ID。
adalConfig.js 定义ADAL配置,并导出一些辅助方法:
import { AuthenticationContext, adalFetch, withAdalLogin } from 'react-adal'; export const adalConfig = { tenant: '{tenant-id-or-domain-name}', clientId: '{app-id-of-native-client-app}', endpoints: { api: 'https://graph.microsoft.com' // <-- The Azure AD-protected API }, cacheLocation: 'localStorage', }; export const authContext = new AuthenticationContext(adalConfig); export const adalApiFetch = (fetch, url, options) => adalFetch(authContext, adalConfig.endpoints.api, fetch, url, options); export const withAdalLoginApi = withAdalLogin(authContext, adalConfig.endpoints.api);index.js
indexApp.js使用
runWithAdalfrom中的方法进行包装
react-adal,以确保在加载之前使用Azure AD对用户进行签名
indexApp.js:
import { runWithAdal } from 'react-adal'; import { authContext } from './adalConfig'; const DO_NOT_LOGIN = false; runWithAdal(authContext, () => { // eslint-disable-next-line require('./indexApp.js'); },DO_NOT_LOGIN);indexApp.js 只是加载并呈现的实例
App,在这里没什么花哨的:
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();App.js 是发生魔术的简单组件:
- 我们定义一个
state
值。在这种情况下,apiResponse
之所以调用它是因为我们仅显示原始API响应,但是您当然可以根据需要命名该状态(或具有多个状态值)。 - 在期间
componentDidMount
(在元素在DOM中可用之后运行),我们调用adalApiFetch
。我们传入fetch
(从Fetch API作为fetch
参数,传入我们要发出的REST请求的/me
端点(在本例中为Microsoft Graph 的端点): - 在该
render
方法中,我们仅在<pre>
元素中显示此状态值。
import React, { Component } from 'react'; import { adalApiFetch } from './adalConfig'; class App extends Component { state = { apiResponse: '' }; componentDidMount() { // We're using Fetch as the method to be called, and the /me endpoint // from Microsoft Graph as the REST API request to make. adalApiFetch(fetch, 'https://graph.microsoft.com/v1.0/me', {}) .then((response) => { // This is where you deal with your API response. In this case, we // interpret the response as JSON, and then call `setState` with the // pretty-printed JSON-stringified object. response.json() .then((responseJson) => { this.setState({ apiResponse: JSON.stringify(responseJson, null, 2) }) }); }) .catch((error) => { // Don't forget to handle errors! console.error(error); }) } render() { return ( <div> <p>API response:</p> <pre>{ this.state.apiResponse }</pre> </div> ); } } export default App;


